I am trying to move a picture to a file call upload , but I insert the data in the database the picture is not uploading in the file upload
$sql = "INSERT INTO tblrecruiter
(Company_Name,Company_Desc,Phone_No,Tel_No,
Company_Pic,State_id,Address,Email,
Password,company_website_url)
VALUES (:Company_Name,:Company_Desc,:Phone_No,:Tel_No,
:Company_Pic,:State_id,:Address,:Email,
:Password,:company_website_url)";
$filename= $_FILES['Company_Pic']['name'];
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':Company_Name' => $_POST['txtcompanyName'],
':Company_Desc' => $_POST['textDesc'],
':Phone_No' => $_POST['txtphoneNum'],
':Tel_No' => $_POST['txttel'],
':Company_Pic' => $filename,
':State_id' => $_POST['txtstate'],
':Address' => $_POST['txtaddress'],
':Email' => $_POST['txtemail'],
':Password' =>$check,
':company_website_url' => $_POST['textcompanylink']));
move_uploaded_file($_FILES["Company_Pic"]["tmp_name"], "../mojob/upload" . $filename);
base on this code:
<?php
error_reporting(0);
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
$filename = $_FILES["uploadfile"]["name"];
$tempname = $_FILES["uploadfile"]["tmp_name"];
$folder = "./image/" . $filename;
$db = mysqli_connect("localhost", "root", "", "database");
// Get all the submitted data from the form
$sql = "INSERT INTO image (filename) VALUES ('$filename')";
// Execute query
mysqli_query($db, $sql);
// Now let's move the uploaded image into the folder: image
if (move_uploaded_file($tempname, $folder)) {
echo "<h3> Image uploaded successfully!</h3>";
} else {
echo "<h3> Failed to upload image!</h3>";
}
}
?>
Related
I have a dashboard where users can login and upload a profile picture of themselves which saves to their profile. This moves the image to the correct folder and also correctly inserts it into the db.
This has been working fine up until recently when I noticed the image disappeared. Within the inspect console I noticed I was getting a 404 not found error on the image, so I checked inside the file path and the image was no longer in there (hence the 404). There is no script at all for the user to delete an image, only to upload.
profile.php:
<p><b>Profile Picture: </b>
<?php
$picture = $row['imagePath'];
if (empty($picture)){
echo "<img src='profiles/no-image.png' width='100' height='100' >";
} else {
echo "<img src='profiles/".$row['imagePath']."' width='100' height='100' >";
};
?>
<form action="scripts/edit-picture.php" method="POST" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="edit-picture" value="Upload"/>
</p>
</form>
script for edit-image.php
<?php
require 'db.php';
session_start();
$uploadDir = '../profiles/';
// if edit-picture has been clicked on, run this if statement
if (isset($_POST['edit-picture'])) {
$studentID = $_SESSION['studentID'];
// Creating 4 different variables using the $_FILES global variable to get data about the image that
// you can view data about a file by doing: print_r($image);
$fileName = $_FILES['image']['name'];
$tmpName = $_FILES['image']['tmp_name'];
$fileSize = $_FILES['image']['size'];
$fileType = $_FILES['image']['type'];
$filePath = $uploadDir.$fileName;
// The below doesn't work as it assigns different value to folder and in db for image name
// $filePath = md5($file_name . microtime()) . substr($fileName , -5, 5);
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
header("Location: ../profile.php?img=errorFileRelocate");
exit;
}
// Checking file size - working
else if ($_FILES["image"]["size"] > 5000000) {
header("Location: ../profile.php?img=errorFileSizeError");
exit();
}
// Check if file name already exists in db - not working
else if (file_exists($result)) {
header("Location: ../profile.php?img=errorFileNameExists");
exit();
}
// Allow certain file formats - not working
else if($result != "jpg" && $result != "png" && $result != "jpeg") {
header("Location: ../profile.php?img=errorFileTypeError");
exit();
}
// This is to show any errors that may occur if the connection fails, this helps with error checking.
else if(mysqli_connect_errno()){
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
else {
$stmt = $conn->prepare ("INSERT INTO `profileImage` (`imagePath`, `studentID`)
VALUES ( ?, ?) ON DUPLICATE KEY UPDATE `imagePath` = VALUES (`imagePath`) ");
$stmt->bind_param("si", $fileName, $studentID);
$stmt->execute() or die("Failed to insert image into the database");
header("Location: ../profile.php?img=successImageUploaded");
exit();
}
}
?>
My folder structure:
profiles
image1.jpg
image2.jpg
profile.php
scripts
edit-image.php
Has anyone ever come across an image actually disappearing from a folder after it being moved in there via move_uploaded_file as ANY help or guidance would be much appreciated.
Solve conditions for image upload and don't overwrite existing image files:
<?php
require 'db.php';
session_start();
$uploadDir = '../profiles/';
// if edit-picture has been clicked on, run this if statement
if (isset($_POST[ 'edit-picture' ])) {
$studentID = $_SESSION[ 'studentID' ];
// Creating 4 different variables using the $_FILES global variable to get data about the image that
// you can view data about a file by doing: print_r($image);
$fileName = $_FILES[ 'image' ][ 'name' ];
$tmpName = $_FILES[ 'image' ][ 'tmp_name' ];
$fileSize = $_FILES[ 'image' ][ 'size' ];
$fileType = $_FILES[ 'image' ][ 'type' ];
$filePath = $uploadDir . $fileName;
// The below doesn't work as it assigns different value to folder and in db for image name
// $filePath = md5($file_name . microtime()) . substr($fileName , -5, 5);
if (file_exists($filePath)) {
header("Location: ../profile.php?img=errorFileNameExists");
exit();
} // Checking file size - working
else if ($_FILES[ "image" ][ "size" ] > 5000000) {
header("Location: ../profile.php?img=errorFileSizeError");
exit();
}
$info = getimagesize($tmpName);
// empty $info - not known image
if (empty($info)) {
header("Location: ../profile.php?img=errorFileTypeError");
exit();
} // This is to show any errors that may occur if the connection fails, this helps with error checking.
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
header("Location: ../profile.php?img=errorFileRelocate");
exit;
}
else if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
} else {
$stmt = $conn->prepare("INSERT INTO `profileImage` (`imagePath`, `studentID`)
VALUES ( ?, ?) ON DUPLICATE KEY UPDATE `imagePath` = VALUES (`imagePath`) ");
$stmt->bind_param("si", $fileName, $studentID);
$stmt->execute() or die("Failed to insert image into the database");
header("Location: ../profile.php?img=successImageUploaded");
exit();
}
}
?>
I have an image upload index for a project. An link to the image is created and saved to a phpMyAdmin DB and the image is supposed to save to my /image folder in the project files. The index saves the link/directory access in the DB but the image itself is not saved. So essentially I have a link to an empty image in my image folder!
I had no issues with the code until I moved from a localhost to a blacknight server.
Any suggestions would be greatly appreciated.
I have tried using BLOB instead of TEXT for images in the database and that has not worked.
I have given permissions to access that for Read/Write in FileZilla.
I have corrected all the DB connections and file paths.
<?php
// Create database connection
$db = mysqli_connect("*HOST*", "*USERNAME*", "*PASSWORD*", "*DB_NAME*");
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = $_FILES['image']['name'];
// Get text
$image_text = mysqli_real_escape_string($db, $_POST['image_text']);
$regplate = $_POST['regplate'];
// image file directory
$target = "/wwwroot/*DOMAIN_NAME*/images/".basename($image);
$sql = "INSERT INTO images (regplate, image, image_text) VALUES ('$regplate', '$image', '$image_text')";
// execute query
mysqli_query($db, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
$result = mysqli_query($db, "SELECT * FROM images");
?>
I expected that this line would submit the file into the /images folder
// image file directory
$target = "/wwwroot/*DOMAIN_NAME*/images/".basename($image);
No need of specifying full path to folder
<?php
// Create database connection
$db = mysqli_connect("*HOST*", "*USERNAME*", "*PASSWORD*", "*DB_NAME*");
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = $_FILES['image']['name'];
// Get text
$image_text = mysqli_real_escape_string($db, $_POST['image_text']);
$regplate = $_POST['regplate'];
// image file directory
$target = "./images/".basename($image);
$sql = "INSERT INTO images (regplate, image, image_text) VALUES ('$regplate', '$image', '$image_text')";
// execute query
mysqli_query($db, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
$result = mysqli_query($db, "SELECT * FROM images");
?>
I have a small form to add categories. My table fields are the following:
Name Required
Description Not Required
Photo Not Required
It will create a category with all the information, it will even insert the image name in the database.
The problem I am having is it will not move the image to the uploads folder.
Also it will rename the image as follows: If image name is avatar.jpg it will rename it 85789avatar.jpg in the database field.
I need it to rename the image as follows O1CCJDSXBOM2.jpg.
and the last issue is the image is not required and if you leave it blank it still puts 89439 numbers in the database field.
if (isset($_POST['submit'])) {
$Name = $_POST['name'];
$Description = $_POST['description'];
if (empty($Name)) {
$errors[] = "Name Required.";
}
if (!empty($errors)) {
echo validation_errors($errors[0]);
} else {
$file = rand(1000, 100000). $_FILES['photo']['name'];
$file_loc = $_FILES['photo']['tmp_name'];
$file_size = $_FILES['photo']['size'];
$folder = "uploads/";
if (($file_size > 2097152)) {
echo validation_errors("Your avatar exceeds file size");
} else {
move_uploaded_file($file_loc, $folder, $file);
$db = dbconnect();
$stmt = $db->prepare("INSERT INTO discussion_categories(Name, Description, Photo) VALUES (?,?,?)");
$stmt->bind_param('sss', $Name, $Description, $file);
$stmt->execute();
$stmt->close();
header("Location: managecategories.php");
it will not move the image to the uploads folder also it will rename the image as follows. if image name is avatar.jpg ti will rename it 85789avatar.jpg in the database field
move_uploaded_file() takes two arguments, not three. Update this line:
move_uploaded_file($file_loc, $folder, $file);
To this (to append the filename to the folder):
move_uploaded_file($file_loc, $folder . $file);
the last issue is the image is not required and if you leave it blank it still puts 89439 numbers in the database field.
Because move_uploaded_file() returns a boolean, the code could be updated to only insert a record if the file was successfully uploaded.
if (move_uploaded_file($file_loc, $folder . $file)) {
$db = dbconnect();
$stmt = $db->prepare("INSERT INTO discussion_categories(Name, Description, Photo) VALUES (?,?,?)");
$stmt->bind_param('sss', $Name, $Description, $file);
$stmt->execute();
$stmt->close();
}
is there an easy way to resize an image before uploading. Been looking for a while now but nothing seems to be working well for me. I want to resize everything to ratio and only resize if something is bigger then lets say 150. Height should move down so the image still looks as it should. I have the following code which works for uploading and renaming but now i want to implement a resize on top of this
$uploadDir = 'images/'; //Image Upload Folder
$fileName = $_FILES['file-0']['name'];
$tmpName = $_FILES['file-0']['tmp_name'];
$fileSize = $_FILES['file-0']['size'];
$fileType = $_FILES['file-0']['type'];
$temp = explode(".", $fileName);
$newfilename = $id . round(microtime(true)) . '.' . end($temp);
$result = move_uploaded_file($_FILES["file-0"]["tmp_name"], "images/" . $newfilename);
$filePath = $uploadDir . $newfilename;
if (!$result) {
echo "Error uploading file";
exit;
}
$query = "
update
pictures SET picture = '$filePath' Where
id = :id
";
$query_params = array(
':id' => $id
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
} catch (PDOException $ex) {
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
You can use php class from the address below. I tried and it works like a charm. It resizes images on the fly.
http://www.bitrepository.com/resize-an-image-keeping-its-aspect-ratio-using-php-and-gd.html
You can check this link below too, to have an idea:
PHP upload and resize image
I am trying to create a script that enter details from a book. The image variable 'image' and 'content' is supposed to be a jpg or PDF. These are selected in the HTML create form of type 'file'.
I've been looking online at other peoples code as I am really struggling to get my head around it.
Heres what I have so far:
require_once __DIR__.'/config.php';
$dbh = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_USERNAME, DB_USERNAME, DB_PASSWORD);
if (isset($_POST['submit'])) {
$title = $_POST["title"];
$authors = $_POST["authors"];
$description = $_POST["description"];
$price = $_POST["price"];
$image = $_POST["image"];
$content = $_POST["content"];
$uploadDir = 'path/to/where/i/can/save/';
if(isset($_POST['submit']))
$fileName = $_FILES['image']['name'];
$tmpName = $_FILES['image']['tmp_name'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$stmt = $dbh->prepare("INSERT INTO books (title, authors, description, price, image, content ) ".
"VALUES ('$title', '$authors', '$description', '$price', '$filepath', '$content')");
$stmt->execute();
}
Not surprisingly this does not do anything, the database remains empty and the page i'm presented with has nothing on it. Can anyone help me sort this out and also tell me how I could make it so that the content is also saved as a filepath.
Sidenote:
In the database i used VARCHAR to store the variables.