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();
}
Related
I am creating a social site that allows people to upload pictures. I am using tempnam() to make each image name unique. But I have a problem.
The tempnam() function seems to be saving the full path in the DB even though I am not trying to use the full path and because of that I can't retrieve the pictures from the folder. There doesn't seem to be any other questions related to mine. Can someone help me ?
$picToUpload = tempnam("assets/images/profile_pics/", '');
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $picToUpload);
$fileExtension = ".png";
rename($picToUpload, $withoutExt . $fileExtension);
$new_file_name = $withoutExt . $fileExtension;
if( !move_uploaded_file($file_tmp, $picToUpload)) {
$errors = "Error uploading files";
die();
}
$path = move_uploaded_file($new_file_name, "assets/images/profile_pics/");
$file_path = $new_file_name;
unlink($picToUpload);
$stmt = $con->prepare("UPDATE users SET profile_pic = ? WHERE username = ?");
$stmt->bind_param('ss', $file_path, $username);
$stmt->execute();
$stmt->close();
header('Location: profile.php');
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");
?>
My upload form for images is working good. Save name and path to database. I want to save full url to image along whit name instead just a name. What I mean is now in DB is saved file_name.jpg I want to save http://example.com/images/file_name.jpg. Here is the upload.php
define('MAX_FILE_SIZE', 20000000430);
$uploadDir = "../../img/";
$permitted = array('image/jpeg', 'image/jpeg', 'image/png', 'image/gif');
$fileName = $_FILES['image']['name'];
$tmpName = $_FILES['image']['tmp_name'];
$fileSize = $_FILES['image']['size'];
$fileType = $_FILES['image']['type'];
// make a new image name
$ext = substr(strrchr($fileName, "."), 1);
// generate the random file name
$randName = md5(rand() * time());
// image name with extension
$myFile = $randName . '.' . $ext;
// save image path
$path = $uploadDir . $myFile;
if (in_array($fileType, $permitted))
{
$result = move_uploaded_file($tmpName, $path);
if (!$result)
{
echo "Error uploading image file";
exit;
}
else
{
// keep track post values
$name = $_POST['name'];
$description = $_POST['description'];
// update data
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE food set name = ?, image = ?, path = ?, description = ?
WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name,$myFile,$path,$description,$id));
Database::disconnect();
echo "<code>Information updated!!</code>";
}
}
What I try is to put the URL in $uploadDir.
$uploadDir = "http://example.com/img/";
But I get this error.
Warning: move_uploaded_file(http://example.com/img/75a13564a8f3305fb0a30ab95487b8de.jpg): failed to open stream: HTTP wrapper does not support writeable connections
Also tried something like this and got same error
define('domainURL', 'http://'.$_SERVER['HTTP_HOST']);
$path = domainURL . $uploadDir . $myFile;
The move_uploaded_file function does not accept file url.
It accepts image actual path.
Because, your file is getting moved physically.
e.g. $path = $_SERVER['DOCUMENT_ROOT'] . 'img/'
You may use relative or absolute path.
Relative path is "../../img/";
Absolute path should be like "/www/htdocs/img/"; (you can see absolute path in FTP client)
And you cannot use URL.
For store in DB use another one variable with URL
assign the upload path in a php variable and use $path to store it in database..
$path = "www.sitename.com/uploads/".$filename ;
I have been trying to change the name of a file after an upload with my script.
I want every file to be named as "testing". Later I am going to change "testing" to a
variable that gets a unique name. Now I just want to change the name to "testing".
Also the script always says error although the file are uploaded.
Can I get some help here please?
Here is my code:
<?php
$uploadDir = 'images/'; //Image Upload Folder
if(isset($_POST['Submit']))
{
$fileName = $_FILES['Photo']['name'];
$tmpName = $_FILES['Photo']['tmp_name'];
$fileSize = $_FILES['Photo']['size'];
$fileType = $_FILES['Photo']['type'];
$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);
}
$query = "INSERT INTO $db_table ( Image ) VALUES ('$filePath')";
mysql_query($query) or die('Error, query failed');
}
?>
I think you need
$fileName = "testing"; //maybe add extension
instead of getting original filename from $_FILES. Although after the file is moved you may end up with a situation of overwriting existing files as they all has the same name. To prevent that (for testing purposes) you may add something to $fileName, maybe a short random string.
Below I have included my code that uploads multiple images to a folder and the path to mysql. I am brand new so please excuse me for such a silly question but I can not figure where to start with sending this timestamp or $fileName value to mysql.
<?php
require_once('storescripts/connect.php');
mysql_select_db($database_phpimage,$phpimage);
$uploadDir = 'upload/';
if(isset($_POST['upload']))
{
foreach ($_FILES as $file)
{
$fileName = $file['name'];
$tmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileType = $file['type'];
if ($fileName != ""){
$filePath = $uploadDir;
$fileName = str_replace(" ", "_", $fileName);
//Split the name into the base name and extension
$pathInfo = pathinfo($fileName);
$fileName_base = $pathInfo['fileName'];
$fileName_ext = $pathInfo['extension'];
//now we re-assemble the file name, sticking the output of uniqid into it
//and keep doing this in a loop until we generate a name that
//does not already exist (most likely we will get that first try)
do {
$fileName = $fileName_base . uniqid() . '.' . $fileName_ext;
} while (file_exists($filePath.$fileName));
$result = move_uploaded_file($tmpName, $filePath.$fileName);
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$fileinsert[]=$filePath;
}
$cat=$_POST['cat'];//this is the category the product is stored in
$about=$_POST['about'];//this is some general information about the item
$price=$_POST['price'];//the price of the item
$item=$_POST['item'];//the name of the item
$name1=basename($_FILES['image01'][$fileName]);//the file name of the first actual jpg
$name2=basename($_FILES['image02'][$fileName]);//the file name of the sencond actual jpg
$name3=basename($_FILES['image03'][$fileName]);//the file name of the third actual jpg
$name4=basename($_FILES['image04'][$fileName]);//the file name of the fourth actual jpg
$query = "INSERT INTO image (mid, cid, about, price, item, name1, name2, name3, name4) ".
"VALUES ('','$cat','$about','$price','$item','$name1','$name2','$name3','$name4')";
mysql_query($query) or die('Error, query failed : ' . mysql_error()); }
?>
If I understand your question correctly, you need to change:
$fileinsert[]=$filePath;
to:
$fileinsert = array(); // initialize the variable before the loop
...
$fileinsert[]=$filePath.$fileName; // or just $fileName if you don't need the path in the DB
and then you need to change:
$name1=basename($_FILES['image01'][$fileName]);//the file name of the first actual jpg
$name2=basename($_FILES['image02'][$fileName]);//the file name of the sencond actual jpg
$name3=basename($_FILES['image03'][$fileName]);//the file name of the third actual jpg
$name4=basename($_FILES['image04'][$fileName]);//the file name of the fourth actual jpg
to:
$name1=$fileinsert[0];
$name2=$fileinsert[1];
$name3=$fileinsert[2];
$name4=$fileinsert[3];
Something like that should do it.