PHP- file uploading working on localhost but not in server (linux) - php

Upload file not working on server but it is working on localhost. File upload permission is ON, but even getting error. I tried all the solution over internet.
Here is my code.
if($submit == "UPLOAD PROFILE PICTURE") {
$user = $_COOKIE['userId'];
$file_name = $_FILES['userPic']['name'];
$file_size =$_FILES['userPic']['size'];
$file_tmp =$_FILES['userPic']['tmp_name'];
$file_type=$_FILES['userPic']['type'];
$tmp = explode('.', $file_name);
$file_ext = end($tmp);
$expensions= array("jpeg","jpg","png");
$nameToStore = $user.".".$file_ext;
chmod("images/users-dp/$nameToStore",0777);
if(in_array($file_ext,$expensions)=== true){
if($file_size < 2097152){
if(move_uploaded_file($file_tmp,"images/users-dp/".$nameToStore)) {
$queryFoCheck = "SELECT * FROM profilepic WHERE user = '$user'";
$resultFoCheck = $connection -> query($queryFoCheck);
$countFoCheck = mysqli_num_rows($resultFoCheck);
if($countFoCheck>=1) {
$query = "UPDATE profilepic SET piclink = '$nameToStore' WHERE user = '$user'";
$result = $connection -> query($query);
} else {
$query = "INSERT INTO profilepic VALUES ('$user', '$nameToStore') ";
$result = $connection -> query($query);
}
header('Location: profile.php?s'); //successsfully updated
} else {
header('Location: profile.php?e=1'); //Cant update
}
} else {
header('Location: profile.php?e=2'); //Cant update
}
} else {
header('Location: profile.php?e=3'); //Cant update
}
}

Related

How to update mysqli field if the value is not empty

I am trying to update a specific value from my table getting them as row from a table let's say the name but the problem is the image, cause i can't pass a value to an input field type = file
I need to update the value in the database only if there is a value to change if not don't change the value that already is there.
My query looks like this and i would like to know what i can change to update image value only if there is a value
//image upload + validation
$file = $_FILES['image'];
$file_name = $_FILES['image']['name'];//file name
var_dump($file_name);
$file_location = $_FILES['image']['tmp_name']; //temporary location
$file_size = $_FILES['image']['size'];// size
$file_error = $_FILES['image']['error'];// error 0 if no error or 1 if there is an error
$temp_extension = explode('.',$file_name);//explode from . file extension, we have file name and extension
$file_extension = strtolower(end($temp_extension)); // extension name (end return the last element of the array)
$allowed_extensions = array('jpg', 'jpeg', 'png', 'pdf');
if (empty($file_name)) {
if (in_array($file_extension, $allowed_extensions)) {
if ($file_error === 0) {
if ($file_size < 15728640) { //15728640b(bytes binary) 15mb mediumblob
$new_file_name = uniqid('',true).".".$file_extension;
// var_dump($new_file_name);
$file_destination = dirname(__FILE__, 2)."/images/".$new_file_name;
move_uploaded_file($file_location, $file_destination);
}else {
echo "Sorry your file size it's too big!";
}
}else {
echo "Sorry, there was an error, try again";
}
}else {
echo "Sorry, your file type is not accepted";
}
}
if(is_array($row)) {
$sql = "UPDATE `accommodation` SET `name` = '{$_POST['name']}', `image` = '$new_file_name', `description` = '{$_POST['description']}', `adress` = '{$_POST['adress']}', `link` = '{$_POST['link']}' WHERE `id` = '{$_POST['id']}'";
mysqli_query(get_connection(), $sql);
var_dump($sql);
// header("Location: admin.php?page=accommodation_list");
}else{
$conn = get_connection();
$sql = "INSERT INTO `accommodation` (`name`, `image`, `description`, `adress`, `link`) VALUES ('{$_POST['name']}', '$new_file_name', '{$_POST['description']}', '{$_POST['adress']}', '{$_POST['link']}')";
mysqli_query($conn, $sql);
$accommodation_id = mysqli_insert_id($conn);
header("Location: admin.php?page=room_add_edit");
}//end if else
This is the query that i need to change but i don't know how....
$sql = "UPDATE `accommodation` SET `name` = '{$_POST['name']}', `image` = '$new_file_name', `description` = '{$_POST['description']}', `adress` = '{$_POST['adress']}', `link` = '{$_POST['link']}' WHERE `id` = '{$_POST['id']}'";
I am aware of SQL injection but first i need this query to work then i will work on SQL injection, and i typed address as adress and i have to change that too.
I have changed the code to this but i don't know if it's a good way to do it
//image upload + validation
$file = $_FILES['image'];
$file_name = $_FILES['image']['name'];//file name
var_dump($file_name);
$file_location = $_FILES['image']['tmp_name']; //temporary location
$file_size = $_FILES['image']['size'];// size
$file_error = $_FILES['image']['error'];// error 0 if no error or 1 if there is an error
$temp_extension = explode('.',$file_name);//explode from . file extension, we have file name and extension
$file_extension = strtolower(end($temp_extension)); // extension name (end return the last element of the array)
$allowed_extensions = array('jpg', 'jpeg', 'png', 'pdf');
if (!empty($file_name)) {
if (in_array($file_extension, $allowed_extensions)) {
if ($file_error === 0) {
if ($file_size < 15728640) { //15728640b(bytes binary) 15mb mediumblob
$new_file_name = uniqid('',true).".".$file_extension;
// var_dump($new_file_name);
$file_destination = dirname(__FILE__, 2)."/images/".$new_file_name;
move_uploaded_file($file_location, $file_destination);
$text1 = "`image` = '$new_file_name',";
}else {
echo "Sorry your file size it's too big!";
}
}else {
echo "Sorry, there was an error, try again";
}
}else {
echo "Sorry, your file type is not accepted";
}
}else {
$text1 = "";
}
if(is_array($row)) {
$sql = "UPDATE `accommodation` SET `name` = '{$_POST['name']}', $text1 `description` = '{$_POST['description']}', `adress` = '{$_POST['adress']}', `link` = '{$_POST['link']}' WHERE `id` = '{$_POST['id']}'";
mysqli_query(get_connection(), $sql);
var_dump($sql);
// header("Location: admin.php?page=accommodation_list");
}
you can simply check the file uploaded or not using a third variable. If file uploaded than save new file name otherwise save the old file name. So you will not lose your file on update. I am assuming you are getting whole row data in $row so check below code
$is_file_uploaded = 0;
if (empty($file_name)) {
if (in_array($file_extension, $allowed_extensions)) {
if ($file_error === 0) {
if ($file_size < 15728640) { //15728640b(bytes binary) 15mb mediumblob
$new_file_name = uniqid('',true).".".$file_extension;
// var_dump($new_file_name);
$file_destination = dirname(__FILE__, 2)."/images/".$new_file_name;
move_uploaded_file($file_location, $file_destination);
$is_file_uploaded = 1;
}else {
echo "Sorry your file size it's too big!";
}
}else {
echo "Sorry, there was an error, try again";
}
}else {
echo "Sorry, your file type is not accepted";
}
if(is_array($row)) {
$new_file_name = ($is_file_uploaded == 1) ? $new_file_name : $row['image'];
//your code
}
}
You can try this:
$new_file_name = "";
if (!empty($file_name)) {
if (in_array($file_extension, $allowed_extensions)) {
if ($file_error === 0) {
if ($file_size < 15728640) { //15728640b(bytes binary) 15mb mediumblob
$new_file_name = uniqid('',true).".".$file_extension;
// var_dump($new_file_name);
$file_destination = dirname(__FILE__, 2)."/images/".$new_file_name;
move_uploaded_file($file_location, $file_destination);
}else {
echo "Sorry your file size it's too big!";
}
}else {
echo "Sorry, there was an error, try again";
}
}else {
echo "Sorry, your file type is not accepted";
}
}
if(is_array($row)) {
if($new_file_name != ""){
$sql = "UPDATE `accommodation` SET `name` = '{$_POST['name']}', `image` = '$new_file_name', `description` = '{$_POST['description']}', `adress` = '{$_POST['adress']}', `link` = '{$_POST['link']}' WHERE `id` = '{$_POST['id']}'";
}else{
$sql = "UPDATE `accommodation` SET `name` = '{$_POST['name']}', `description` = '{$_POST['description']}', `adress` = '{$_POST['adress']}', `link` = '{$_POST['link']}' WHERE `id` = '{$_POST['id']}'";
}
mysqli_query(get_connection(), $sql);
var_dump($sql);
// header("Location: admin.php?page=accommodation_list");
}

How to save an image to the database with a path file

I am trying to save a picture into my database along with the path file. But what it does now is incorrect. It only saves the image into the database and not the entire image path. What's wrong?
I do the exact same thing with this code in another project and can't wrap my head around the problem here.
$userPic = '';
$date_time = date('Y-m-d_H-i-s');
if(!empty($userLoggedIn)) {
if (isset($_FILES['fileToUpload'])) {
$errors = array();
$file_name = $_FILES['fileToUpload']['name'];
$file_size = $_FILES['fileToUpload']['size'];
$width = 1500;
$height = 1500;
$file_tmp = $_FILES['fileToUpload']['tmp_name'];
$file_type = $_FILES['fileToUpload']['type'];
$tmp = explode('.', $_FILES['fileToUpload']['name']);
$file_ext = strtolower (end ($tmp));
$extensions = array("jpeg", "jpg", "png", "gif");
if(in_array($file_ext, $extensions) === false) {
$errors[] = "extension not allowed. Please choose a JPEG or PNG file.";
}
if ($file_size > 8097152) {
$errors[] = 'File size must be 2 MB';
}
if ($width > 1500 || $height > 1500) {
echo"File is to large";
}
if(!$errors) {
$userPic = md5($_FILES["fileToUpload"]["name"]) . $date_time . " " . $file_name;
move_uploaded_file($file_tmp, "assets/images/profile_pics/" . $userPic);
$stmt = $con->prepare("UPDATE users SET profile_pic = ? WHERE username = ?");
$stmt->bind_param('ss', $userPic, $username);
$stmt->execute();
$stmt->close();
}
}
}
else {
echo "Invalid Username";
}
You can assign another variable that contains both the path and the variable for the image you used, and then use that variable in your query:
$file_path = "assets/images/profile_pics/".$userPic;
Your code:
if(!$errors) {
$userPic = md5($_FILES["fileToUpload"]["name"]) . $date_time . " " . $file_name;
move_uploaded_file($file_tmp,"assets/images/profile_pics/" . $userPic);
$imag_path = "assets/images/profile_pics/" . $userPic;
$stmt = $con->prepare("UPDATE users SET profile_pic = ? WHERE username = ?");
$stmt->bind_param('ss', $imag_path, $username);
$stmt->execute();
$stmt->close();
}
Try this:
You save only the new image name, not path.

how to upload image using php function

This is my code. I tried to upload an image using this PHP code. $mainCName, $mainCImage save in the database. But, the image does not upload to the uploadedimage folder. Can you help me please?.
public function add_main_category($mainCName, $mainCImage){
$query = "SELECT * FROM mainCategory WHERE mainCName='$mainCName'";
$result = $this->db->query($query) or die($this->db->error);
$count_row = $result->num_rows;
if($count_row == 0){
$imgfile=$_FILES["$mainCImage"];
$extension = substr($imgfile,strlen($imgfile)-4,strlen($imgfile));
$allowed_extensions = array(".jpg",".jpeg",".png",".gif");
if(!in_array($extension,$allowed_extensions))
{
echo "<script>alert('Invalid format. Only jpg / jpeg/ png /gif format allowed');</script>";
}
else{
$imgnewfile=md5($imgfile).$extension;
move_uploaded_file($_FILES["mainCImage"]["tmp_name"],"uploadedimage/".$imgnewfile);
}
$query = "INSERT INTO maincategory(mainCName,mainCImage) VALUES('$mainCName','$mainCImage')";
$result = $this->db->query($query) or die($this->db->error);
return true;
}
else{return false;}
}

Unable to store pic link into database

I am trying to upload my pic into folder and file link store into database although file store in folder but unfortunately doesn't store link in database. Please see where I am doing mistake.
<?php
include('dbconnection.php');
if(count($_FILES["file"]["name"]) > 0)
{
sleep(3);
for($count=0; $count<count($_FILES["file"]["name"]); $count++)
{
$file_name = $_FILES["file"]["name"][$count];
$tmp_name = $_FILES["file"]['tmp_name'][$count];
$file_array = explode(".", $file_name);
$file_extension = end($file_array);
if(file_already_uploaded($file_name, $connect))
{
$file_name = $file_array[0] . '-'. rand() . '.' . $file_extension;
}
$location = 'files/' . $file_name;
if(move_uploaded_file($tmp_name, $location))
{
$stmt= $connect->prepare("INSERT INTO tbl_image (image_name) VALUES (:image_name)");
$stmt->bindParam(':image_name', $file_name);
$stmt->execute();
}
}
}
function file_already_uploaded($file_name, $connect)
{
$statement = $connect->prepare("SELECT image_name FROM tbl_image WHERE image_name = '".$file_name."'");
$statement->execute();
$number_of_rows = $statement->rowCount();
if($number_of_rows > 0)
{
return true;
}
else
{
return false;
}
}
?>
store the image name as location with file name:
$location = 'files/' . $file_name;
if(move_uploaded_file($tmp_name, $location))
{
$stmt= $connect->prepare("INSERT INTO tbl_image (image_name) VALUES (:image_name)");
$stmt->bindParam(':image_name', $location.'/'.$file_name);
$stmt->execute();
}

Unexpected result after file upload

This code is to update database. it updates everything even uploads image sucessfully but after image upload the whole page gets blank and only "Array()" is displayed at top. Why is that?
<?php
if(!isset($_GET["prid"])){
header("Location: prjedit.php");
}
else {
$prid = intval($_GET["prid"]);
$sqlprj = "SELECT * FROM projects WHERE id = ? LIMIT 1";
$statement = $db->prepare($sqlprj);
$statement->execute(array($prid));
$project = $statement->fetchObject();
//submitted form
if( (isset($_POST["title"])) && (isset($_POST["details"])) ) {
$title = $_POST['title'];
$desc = $_POST['descr'];
$details = $_POST['details'];
if(!empty($_FILES['image']['name'])) {
//update image
$file = basename($_FILES['image']['name']);
$dir = "projects/";
$target_path = $dir . basename($_FILES['image']['name']);
$tempname = $_FILES['image']['tmp_name'];
if(!file_exists($target_path)) {
if(move_uploaded_file($tempname, $target_path)) {
$sqlimg = "UPDATE projects SET image = ? WHERE id = ?";
$statement = $db->prepare($sqlimg);
$statement->execute(array($file, $prid));
if($statement->rowCount() > 0) {
try {
chdir('./projects/');
unlink($project->image);
chdir('..');
}
catch (Exception $e) {
$message = "Sorry image delete failed ";
echo $e->getMessage();
}
}
else {
die ($db->errorInfo());
}
}
else {
$message = "Sorry Image update failed";
}
}
else {
$message = "Sorry this image already exists but text";
}
}
// update project texts
$sqlupd = "UPDATE projects SET title = ?, descinfo = ?, details = ? WHERE id = ?";
$statement = $db->prepare($sqlupd);
$statement->execute(array($title, $desc, $details, $prid));
if($statement->rowCount()) {
$message = " Saved successfully";
}
else {
die($db->errorInfo());
}
}
}
?>
Looking at Pdo::codeInfo documentation, it returns an array.
When you write die($db->errorInfo()); it will try to display this array.
As suggested by the documentation itself, you could try print_r($db->errorInfo()); die; and see what happens.

Categories