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();
Related
I try using function to upload different kind of file by giving it variables. As shown below:
<?
function fn_fileUpload($data,$dir,$uid){
include_once($_SERVER['DOCUMENT_ROOT']."/cgi-bin/connect.php");
if(isset($data) && $data['error'] === UPLOAD_ERR_OK){
$fileTmpPath = $data['tmp_name'];
$fileName = $data['name'];
$fileSize = $data['size'];
$fileType = $data['type'];
$fileNameCmps = explode(".", $fileName);
$fileExt = strtolower(end($fileNameCmps));
$newFileName = $uid . '.' . $fileExt;
//check file ext
$okEXT = array('jpg', 'jpeg', 'png','doc','docx','pdf');
if (in_array($fileExt, $okEXT)) {
$fileDir = '/'.$dir.'/';
$dest_path = $fileDir.$newFileName;
if(move_uploaded_file($fileTmpPath, $dest_path)){
try{
$stmt2=$mysqli->prepare("insert into job_file (jfile_id, job_id, jfile_name, jfile_size, jfile_type, jfile_ext) valies(?,?,?,?,?,?)");
$stmt2->bind_param('iisiss',$zero,$uid,$newFileName,$fileSize,$fileType,$fileExt);
$stmt2->execute();
$result = 'ok';
}catch(mysqli_sql_exception $err){
$result=$err;
}
}else{
$result = 'Cannot upload file!';
}
}//in_array
}//if(isset
return $result;
}
?>
And this is how to use:
//upload file
$job_file=fn_fileUpload($_FILES['job_file'],'uploads',$_POST['passport_id']);
//upload photo
$job_img=fn_fileUpload($_FILES['job_img'],'photos',$_POST['passport_id']);
From here, the function always return : Cannot upload file!. At first I think. It might have something to do with move_uploaded_file but the file was there in /uploads directory but not with /photos. Both directories CHMOD 755 (tried 777 but no luck).
The db went through correctly. Is there any idea how to fix this?
You can only use move_uploaded_file() ONCE on a temporary file that has been uploaded through a form. This function destroys the temporary file after it has been moved, so the for the first upload in the uploads directory you can do it well but in for the second one no.
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
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 want to do is to resize the the image that i will be moving to upload folder using GD enhancer in my image upload script.
My problem is after i try the GD enhancer in my php code i couldn't make it work.
my current php code:
<?php
include_once('../dbc/database.php');
$db = new Connection();
$db = $db->dbConnect();
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
use gdenhancer\GDEnhancer;
include_once 'GDEnhancer.php';
$emailCodeResult = isset($_POST['emailCodeResult']) ? $_POST['emailCodeResult'] : "";
$imageLink = isset($_POST['imageLink']) ? $_POST['imageLink'] : "";
const path = "files/upload/";
$s= explode(path,$imageLink);
unlink("../upload/".$s[1]);
$email = isset($_POST['email']) ? $_POST['email'] : "";
$type = $_FILES["imageInput"]["type"];
$ext = end(explode('/', $type));
$filename = uniqid() . '_' .$emailCodeResult . '.' . $ext;
$image = new GDEnhancer($filename);
$image->backgroundResize(300, 300, 'shrink');
$save = $image->save();
header('content-type:' . $save['mime']);
move_uploaded_file($_FILES["imageInput"]["tmp_name"], "../upload/" . $save);
$location = "files/upload/" . $filename;
if(!empty($_POST['email'])) {
$q = "UPDATE tbl_user SET user_image = '$location' WHERE user_email= :email ";
$query = $db->prepare($q);
$query->bindParam(':email', $email);
$results = $query->execute();
echo "1";
}
?>
First, check this link (example #1 Save image to folder)
Second, you don't have to check image type, GDEnhancer will do this for you.
Third, header('content-type:' . $save['mime']) is not necessary if you save file to disk.