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 />';
}
}
}
}
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..
I am trying to upload multiple files using PHP which is working fine. Now in my form, I am displaying the file options dynamically along with the type of document it is, resume, id proof, etc.,
It is not necessary that the user should upload all the files at once, he can select whatever docs he has and use the submit button to upload them, after which I'd like to update that doc status to "Received". While trying to do this, I am seeing that only last record is getting updated no matter how many files are selected.
Here's my Form code -
<table class="table striped bordered border hoverable white">
<?php
$returnMsg = "";
$docsNStatus="SELECT * FROM applicantdocs where username = '$login_session' and docStatus='Not Received'";
if(!$result=mysqli_query($db,$docsNStatus))
die('There was an error retrieving the information');
echo "<form method='POST' action='../../actionHandler.php' enctype='multipart/form-data' target='resultFrame'>";
while ( $row = $result->fetch_assoc() ){
$uploadFileName = "fileUpload".$row['sno'];
$docID = $row['sno'];
echo "<tr>
<td>".$row['docName']."</td>
<td>".$row['docStatus']."</td>
<td>
<input type='hidden' name='docNumber' value='$docID'/>
<input type='hidden' name ='docNumber_$docID' value='$docID'/> //Here I am dynamically setting the hidden element docnumber and the id
<label style= 'padding: 5px!important;' class='myLabel'>
<input type='file' name='uploadingFiles[]' id='uploadBtn'/>
<span>Upload doc</span>
</label>
</td></tr>";
}
echo "</table><br/><input type='submit' name ='uploadFile' value='Click here to upload files' class='formButton'/> ";
?>
PHP code:
if(isset($_POST["uploadFile"])){
$userIDquery = "SELECT firstName, lastName from applicants WHERE username= \"{$login_session}\"";
$userRes= mysqli_query($db, $userIDquery);
$userRec= mysqli_fetch_array($userRes, MYSQLI_ASSOC);
$lName = $userRec["firstName"].'_'.$userRec["lastName"];
$storageLocation = "Assets/Documents/".$lName."/";
$errors = array();
$extension = array('jpg','png','jpeg','gif','pdf');
$bytes = 1024;
$allowedMB = 10;
$totalBytes = $allowedMB * $bytes * 1024;
foreach($_FILES["uploadingFiles"]["tmp_name"] as $key=>$tmp_name) {
$docNo = mysqli_real_escape_string($db, $_POST["docNumber"]);
$onlyDocNumToUpdate = mysqli_real_escape_string($db, $_POST["docNumber_".$docNo]);
$uploadThisFile = true;
$file_name=$_FILES["uploadingFiles"]["name"][$key];
$file_tmp=$_FILES["uploadingFiles"]["tmp_name"][$key];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(!in_array(strtolower($ext),$extension)) {
array_push($errors, "File type is invalid. Name:- ".$file_name);
$uploadThisFile = false;
}
if($_FILES["uploadingFiles"]["size"][$key] > $totalBytes) {
array_push($errors, "File size must be less than 10MB. Name:- ".$file_name);
$uploadThisFile = false;
}
if($uploadThisFile){
$filename=basename($file_name,$ext);
$newFileName=$filename.$ext;
if(move_uploaded_file($_FILES["uploadingFiles"]["tmp_name"][$key], $storageLocation.$newFileName)){
$query = "UPDATE applicantdocs set docStatus ='Received'
where username = '$login_session'
and sno=$onlyDocNumToUpdate";
if(!mysqli_query($db, $query)){
print '<br><b style="color:#B60000">Exception:</b> ';
throw new Exception(showerror($db));
} else
print "The selected files have been uploaded successfully.";
}
}
}
mysqli_close($db);
$count = count($errors);
if($count != 0){
foreach($errors as $error){
echo $error."<br/>";
}
}
}
My form looks something like below -
Appreciate taking a look at it.
I am working on a project where each item could have multiple images, I created a form that would accept the images and store them into an array. The problem is whenever I try inserting the images into a table row in the database it displays an error:
"Array to string conversion"
How can I fix this? And also how do I fetch each images on another page from the same database table. Below is my code.
-Form code
<form method="post" enctype="multipart/form-data" >
<input required type="text" name="name">
<input required type="text" name="location">
<input required type="text" name="status">
<select required name="category">
<option>Category</option>
<option value="construct">Construction</option>
<option value="promgt">Project Development</option>
<option value="archdesign">Architectural Designs</option>
</select>
<textarea required class="form-control" name="descrip" rows="5"></textarea>
<input style="text-align:left" type="file" name="imgs[]" multiple>
<button type="submit" name="submit" formaction="addaction.php">Add Project</button>
</form>
-Addaction.php code
<?php
$db=mysqli_connect("localhost","root","dbpassword","dbname");
if(!empty($_FILES['imgs']['name'][0])){
$imgs = $_FILES['imgs'];
$uploaded = array();
$failed = array();
$allowed = array('jpg', 'png');
foreach($imgs['name'] as $position => $img_name){
$img_tmp = $imgs['tmp_name'][$position];
$img_size = $imgs['size'][$position];
$img_error = $imgs['error'][$position];
$img_ext = explode('.',$img_name);
$img_ext = strtolower(end($img_ext));
if(in_array($img_ext, $allowed)) {
if($img_error === 0){
if($img_size <= 500000) {
$img_name_new = uniqid('', true) . '.' . $img_ext;
$img_destination = 'img/'.$img_name_new;
if(move_uploaded_file($img_tmp, $img_destination)){
$uploaded[$position] = $img_destination;
}else{
$failed[$position] = "[{$img_name}] failed to upload";
}
}else{
$failed[$position] = "[{$img_name}] is too large";
}
}else{
$failed[$position] = "[{$img_name}] error";
}
}else{
$failed[$position] = "[{$img_name}] file extension";
}
}
if(!empty($uploaded)){
print_r($uploaded);
}
if(!empty($failed)){
print_r($failed);
}
}
if(isset($_POST['submit'])){
$name = $_POST['name'];
$location = $_POST['location'];
$status = $_POST['status'];
$descrip = $_POST['descrip'];
$category = $_POST['category'];
$img_name_new = $_FILES['imgs']['name'];
if ($db->connect_error){
die ("Connection Failed: " . $db->connect_error);
}
$sql_u = "SELECT * FROM projects WHERE name='$name'";
$sql_e = "SELECT * FROM projects WHERE category='$category'";
$res_u = mysqli_query($db, $sql_u);
$res_e = mysqli_query($db, $sql_e);
if (mysqli_num_rows($res_u) && mysqli_num_rows($res_e) > 0) {
echo "<div style='margin: 0 80px' class='alert alert-danger' role='alert'> Error. Item Already exists </div>";
header("refresh:3 url=add.php");
}else{
$sql_i = "INSERT INTO items (name, location, status, descrip, imgs, category) VALUES ('$name','$location','$status,'$descrip','$img_name_new','$category')";
}
if (mysqli_query($db, $sql_i)){
echo "Project Added Successfully";
}else{
echo mysqli_error($db);
}
$db->close();
}
?>
$img_name_new = $_FILES['imgs']['name'] is an array of one or more image names.
You will need to decide how you wish to store the array data as a string in your database.
Here are a couple of sensible options, but choosing the best one will be determined by how you are going to using this data once it is in the database.
implode() it -- $img_name_new = implode(',', $_FILES['imgs']['name']);
json_encode() it -- $img_name_new = json_encode($_FILES['imgs']['name']);
And here is my good deed for the year...
Form Script:
<?php
if (!$db = new mysqli("localhost", "root", "", "db")) { // declare and check for a falsey value
echo "Connection Failure"; // $db->connect_error <-- never show actual error details to public
} else {
if ($result = $db->query("SELECT name FROM items")) {
for ($rows = []; $row = $result->fetch_row(); $rows[] = $row);
$result->free();
?>
<script>
function checkName() {
var names = '<?php echo json_encode($rows); ?>';
var value = document.forms['project']['name'].value;
if (names.indexOf(value) !== -1) { // might not work on some old browsers
alert(value + ' is not a unique name. Please choose another.');
return false;
}
}
</script>
<?php
}
?>
<form name="project" method="post" enctype="multipart/form-data" onsubmit="return checkName()">
Name: <input required type="text" name="name"><br>
Location: <input required type="text" name="location"><br>
Status: <input required type="text" name="status"><br>
Category: <select required name="category">
<?php
if ($result = $db->query("SELECT category, category_alias FROM categories")) {
while ($row = $result->fetch_assoc()) {
echo "<option value=\"{$row['category']}\">{$row['category_alias']}</option>";
}
}
?>
</select><br>
<textarea required class="form-control" name="descrip" rows="5"></textarea><br>
<input style="text-align:left" type="file" name="imgs[]" multiple><br>
<button type="submit" name="submit" formaction="addaction.php">Add Project</button>
</form>
<?php
}
*notice that I have made a separate category table for validation.
Submission Handling Script: (addaction.php)
<?php
if (isset($_POST['submit'], $_POST['name'], $_POST['location'], $_POST['status'], $_POST['descrip'], $_POST['category'], $_FILES['imgs']['name'][0])) {
$paths = [];
if (!empty($_FILES['imgs']['name'][0])) {
$imgs = $_FILES['imgs'];
$allowed = array('jpg', 'png');
foreach($imgs['name'] as $position => $img_name){
$img_tmp = $imgs['tmp_name'][$position];
$img_size = $imgs['size'][$position];
$img_error = $imgs['error'][$position];
$img_ext = strtolower(pathinfo($img_name)['extension']);
if (!in_array($img_ext, $allowed)) {
$errors[] = "File extension is not in whitelist for $img_name ($position)";
} elseif ($img_error) {
$errors[] = "Image error for $img_name ($position): $image_error";
} elseif ($img_size > 500000) {
$errors[] = "Image $image_name ($position) is too large";
} else {
$img_destination = 'img/' . uniqid('', true) . ".$img_ext";
if (!move_uploaded_file($img_tmp, $img_destination)) {
$errors[] = "Failed to move $img_name ($position) to new directory";
} else {
$paths[] = $img_destination;
}
}
}
}
if (!empty($errors)) {
echo '<ul><li>' , implode('</li><li>', $errors) , '</li></ul>';
} elseif (!$db = new mysqli("localhost", "root", "", "db")) { // declare and check for a falsey value
echo "Connection Failure"; // $db->connect_error <-- never show actual error details to public
} elseif (!$stmt = $db->prepare("SELECT COUNT(*) FROM categories WHERE category = ?")) {
echo "Prepare Syntax Error"; // $db->error; <-- never show actual error details to public
} elseif (!$stmt->bind_param("s", $_POST['category']) || !$stmt->execute() || !$stmt->bind_result($found) || !$stmt->fetch()) {
echo "Category Statement Error"; // $stmt->error; <-- never show actual error details to public
} elseif (!$found) {
echo "Category Not Found - Project Not Saved";
} else {
$stmt->close();
$cs_paths = (string)implode(',', $paths);
// Set the `name` column in `items` to UNIQUE so that you cannot receive duplicate names in database table
if (!$stmt = $db->prepare("INSERT INTO items (name, location, status, category, descrip, imgs) VALUES (?,?,?,?,?,?)")) {
echo "Error # prepare"; // $db->error; // don't show to public
} elseif (!$stmt->bind_param("ssssss", $_POST['name'], $_POST['location'], $_POST['status'], $_POST['category'], $_POST['descrip'], $cs_paths)) {
echo "Error # bind"; // $stmt->error; // don't show to public
} elseif (!$stmt->execute()) {
if ($stmt->errno == 1062) {
echo "Duplicate name submitted, please go back to the form and change the project name to be unique";
} else {
echo "Error # execute" , $stmt->error; // $stmt->error; // don't show to public
}
} else {
echo "Project Added Successfully";
}
}
}
I am trying to set up a profile page where user can upload a profile picture. The problem I a having is that when the status is changed from 1 to 0 the image changes from a default profile image to a small black box with an "x" in it. Everything else works fine. I thought it might be the css but it is not. If anyone can assist, it would greatly appreciated. Thank you.
Profile.php:
<?php
$id= $_GET['id'];
$sql = "SELECT * FROM user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$sqlImg = "SELECT * FROM profileImg WHERE id='$id'";
$resultImg = mysqli_query($conn, $sqlImg);
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
echo "<div class='userProfileImage'>";
if ($rowImg['status'] == 0 ) {
echo "<img src='images/profile".$id.".jpg'>";
} else {
echo "<img src='images/profile_default.jpg'>";
}
echo "<p>".$row['first']."</p>";
echo "</div>";
}
}
} else {
echo "There are no users yet!";
}
uploadProfile.php:
<?php
session_start();
include '../dbh.php';
$id = $_SESSION['id'];
$userID = $id;
if (isset($_POST['submit'])) {
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileERROR = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'gif', 'png', 'mov', 'mpeg4', 'mp4', 'avi', 'wmv', 'mpegps', 'flv', '3gpp', 'webm');
if (in_array($fileActualExt, $allowed)) {
if ($fileERROR === 0) {
if ($fileSize < 500000) {
$fileNameNew = "profile".$id.".".$fileActualExt;
$fileDestination = '../uploads/'.$fileNameNew;
$sql = "UPDATE profileImg SET status=0 WHERE id='$id'";
$result = mysqli_query($conn, $sql);
move_uploaded_file($fileTmpName, $fileDestination);
header("Location: ../profile.php?id=$userID");
} else {
echo "Your file is too large";
}
} else {
echo "There was an error uploading your file";
}
} else {
echo "You cannot upload files of this type";
}
}
?>
Files are being uploaded to uploads as line below
$fileDestination = '../uploads/'.$fileNameNew;
and img src is
echo "<img src='images/profile".$id.".jpg'>";
Please update you code.
Edit: you are allowing multiple extensions to be uploaded and on profile.php single extension is used to load the picture.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
i am updating name , email in DB of registered user through php form. its working fine.
class.usr.php
public function update($uname,$email, $tax)
{
try {
$stmt = $this->conn->prepare('UPDATE tbl_users SET userName = ?, userEmail = ? , tax = ? WHERE userID = ? ');
$stmt->execute(array($uname,$email, $tax , $_SESSION['userSession']));
return $stmt->fetch();
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
form
<form action="profile.php" method="POST" enctype="multipart/form-data">
Name :
<input type="text" name="txtuname" value="<?php echo $row['userName'] ?>" /><br/>
Email :
<input type="text" name="txtemail" value="<?php echo $row['userEmail'] ?>" /><br>
Image
<input type="file" name="photo" id="fileSelect"><br>
<input type="submit" name="submit" value="Save" />
</form>
form related code to save in db
<?php
$user_home = new USER();
if(!$user_home->is_logged_in())
{
header("Location: index.php");
die();
}
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$tax = trim($_POST['tax']); // image url path
$uid = (isset($_SESSION['userSession']) ? intval($_SESSION['userSession']) : 0);
if ($uid > 0 && $user_home->update($uname,$email, $tax, $uid))
{
header("Location: profile1.php");
die();
}
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
after this, now i am uploading an image to folder through same php form successfully with below code.
<?php
if(isset($_FILES["photo"]["error"])){
if($_FILES["photo"]["error"] > 0){
echo "Error: " . $_FILES["photo"]["error"] . "<br>";
} else{
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/" . $_FILES["photo"]["name"])){
echo $_FILES["photo"]["name"] . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]);
echo "Your file was uploaded successfully.";
}
} else{
echo "Error: There was a problem uploading your file - please try again.";
}
}
} else{
echo "";
}
?>
now images are just saving in folders, what i need is i want that image path to save in database and assign that image path to uploaded user in database. so that one registered user can update the existing image, but not upload one more image.
i tried below code , but not working:
<?php
$folder = "upload/";
$file = basename( $_FILES['image']['name']);
$full_path = $folder.$file;
$tax= $full_path;
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/" . $_FILES["photo"]["name"])){
echo $_FILES["photo"]["name"] . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]);
echo "Your file was uploaded successfully.";
}
} else{
echo "Error: There was a problem uploading your file - please try again.";
}
}
} else{
echo "";
}
?>
db columns : userName, userEmail, tax , photo
with help of google i done all above, i am new to php, so please kindly help me.
Here is another solution:
First of all execute this query manually to add the new column:
ALTER TABLE `tbl_users` ADD `photo` VARCHAR(255) NOT NULL ;
Then this is the php code:
<?php
$dbConn = new Database();
$dbConn->dbConnection();
$user_home = new USER();
function uploadUserPhoto($uid) {
global $dbConn;
if(isset($_FILES["photo"]["error"])) {
if($_FILES["photo"]["error"] > 0) {
echo "Error: " . $_FILES["photo"]["error"] . "<br>";
} else {
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
$userDir = $uid;
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if(in_array($filetype, $allowed)) {
if(!is_dir('upload/'.$uid)) {
mkdir('upload/'.$uid);
}
$photoname = time().$uid.'_photo'.'.'.$ext;
// delete all the files in this directory
$files = glob('upload/'.$uid.'/*'); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file))
unlink($file); // delete file
}
// Upload the photo
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $uid . '/'. $photoname);
$updateData = array(':userID' => $uid, ':photo' => $photoname);
$stmt = $dbConn->conn->prepare("UPDATE tbl_users SET photo=:photo WHERE userID=:uid");
$stmt->execute($updateData);
echo "Your file was uploaded successfully.";
} else {
echo "Error: There was a problem uploading your file - please try again.";
}
}
} else {
echo "";
}
}
if(!$user_home->is_logged_in())
{
header("Location: index.php");
die();
}
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$tax = trim($_POST['tax']); // image url path
$uid = (isset($_SESSION['userSession']) ? intval($_SESSION['userSession']) : 0);
if ($uid > 0 && $user_home->update($uname,$email, $tax, $uid))
{
uploadUserPhoto($uid);
header("Location: profile1.php");
die();
}
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
There is $dbConnection variable which is the connection to the DB but because I don't know the rest of your code you should replace it with your proper db connection variable.
The photo of the user is saved in photo column in tbl_users and for every user is created sub dir in uploads dir. The subdir is the userID. So for example for user with userID = 1 its upload path will be uploads/1/<filename>.
File name is generated dynamically - this avoids caching of uploaded photo with the same name for example ... and it is better approach.
You have to make a change in code for displaying the photo because now its filename is in the DB and there is subdir in uploads (which is the userID of the user)
Add new function for saving files and use global php var $_FILES
1
Add new column to your DB to store file path, let's name it photo
2
Add new functions for your user class:
<?php
class User {
...
const PATH_PHOTOS = '/path/to/photo/folder/';
const BASE_URL = 'http://YOUR_DOMAIN_NAME:YOUR_PORT/YOUR_PATH/';
public function add_photo($file)
{
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$file['new_name'] = uniqid(rand(), true) . ".$ext";
if (!$this->_upload_file($file))
return false;
return $this->_remove_previous_photo()->_add_file_to_db(self::PATH_PHOTOS . basename($file['new_name']));
}
protected function _remove_previous_photo()
{
$photo = $this->get_photo();
if ($photo)
unlink($photo);
return $this;
}
public function get_photo()
{
global $_SESSION;
$stmt = $this->conn->prepare('SELECT photo FROM tbl_users WHERE userID = ? ');
$stmt->execute(array($_SESSION['userSession']));
$result = $stmt->fetch();
return reset($result);
}
public function get_photo_url()
{
$pathInfo = pathinfo($this->get_photo());
$last_dir = end(explode(DIRECTORY_SEPARATOR, $pathInfo['dirname']));
return self::BASE_URL . "$last_dir/" . basename($this->get_photo());
}
protected function _upload_file($file)
{
$uploadfile = self::PATH_PHOTOS . $file['new_name'];
return move_uploaded_file($file['tmp_name'], $uploadfile);
}
protected function _add_file_to_db($file_path)
{
try {
$stmt = $this->conn->prepare('UPDATE tbl_users SET photo = ? WHERE userID = ? ');
return $stmt->execute(array($file_path, $_SESSION['userSession']));
} catch (PDOException $e) {
echo '<p class="bg-danger">' . $e->getMessage() . '</p>';
}
}
...
}
?>
3
The main file should look like this:
<?php
$user_home = new USER();
if(!$user_home->is_logged_in())
{
header("Location: index.php");
die();
}
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$tax = trim($_POST['tax']); // image url path
$uid = (isset($_SESSION['userSession']) ? intval($_SESSION['userSession']) : 0);
if ($uid > 0 && $user_home->update($uname,$email, $tax, $uid) && $user_home->add_photo($_FILES['photo']))
{
header("Location: profile1.php");
die();
}
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
Hope this helps