How to save uploaded image to file using php - php

I have been trying to save uploaded images to a folder using PHP. I have been stuck on this because the name of the image saves differently to the database than the folder.
Database:assets/images/profile_pics/john_doe5a153efc8731359393775e3355df0b77n.jpg
Folder: john_doe_original.5a153efc8731359393775e3355df0b77njpeg
include("includes/header2.php");
$profile_id = $user['username'];
$imgSrc = "";
$result_path = "";
$msg = "";
/***********************************************************
0 - Remove The Temp image if it exists
***********************************************************/
if (!isset($_POST['x']) && !isset($_FILES['image']['name']) ){
//Delete users temp image
$temppath = 'assets/images/profile_pics/'.$profile_id.'_temp.jpeg';
if (file_exists ($temppath)){ #unlink($temppath); }
}
if(isset($_FILES['image']['name'])){
/***********************************************************
1 - Upload Original Image To Server
***********************************************************/
//Get Name | Size | Temp Location
$ImageName = $_FILES['image']['name'];
$ImageSize = $_FILES['image']['size'];
$ImageTempName = $_FILES['image']['tmp_name'];
//Get File Ext
$ImageType = #explode('/', $_FILES['image']['type']);
$type = $ImageType[1]; //file type
//Set Upload directory
$uploaddir = $_SERVER['DOCUMENT_ROOT'].'/name/assets/images/profile_pics';
//Set File name
$file_temp_name = $profile_id.'_original.'.md5(time()).'n'.$type; //the temp file name
$fullpath = $uploaddir."/".$file_temp_name; // the temp file path
$file_name = $profile_id.'_temp.jpeg'; //$profile_id.'_temp.'.$type; // for the final resized image
$finalname = $profile_id.md5(time());
$fullpath_2 = "assets/images/profile_pics/".$finalname."n.jpg"; //for the final resized image
//Move the file to correct location
$move = move_uploaded_file($ImageTempName,$fullpath) ;
chmod($fullpath, 0777);
//Check for valid uplaod
if (!$move) {
die ('File didnt upload');
} else {
$imgSrc= "assets/images/profile_pics/".$file_name; // the image to display in crop area
$msg= "Upload Complete!"; //message to page
$src = $file_name; //the file name to post from cropping form to the resize
}
}
if (isset($_POST['Submit'])){
//Insert image into database
$insert_pic_query = mysqli_query($con, "UPDATE users SET profile_pic='$fullpath_2' WHERE username='$userLoggedIn'");
//header("Location: account.php");
}
Thank you for your help. Let me know how I can improve my question as well.

Use $fullpath_2 in your move_uploaded_file(). change upload directiry to $uploaddir = $_SERVER['DOCUMENT_ROOT'] . '/Halpper/';
if (isset($_FILES['image']['name'])) {
/***********************************************************
* 1 - Upload Original Image To Server
***********************************************************/
//Get Name | Size | Temp Location
$ImageName = $_FILES['image']['name'];
$ImageSize = $_FILES['image']['size'];
$ImageTempName = $_FILES['image']['tmp_name'];
//Get File Ext
$ImageType = #explode('/', $_FILES['image']['type']);
$type = $ImageType[1]; //file type
//Set Upload directory
$uploaddir = $_SERVER['DOCUMENT_ROOT'] . '/Halpper/';
//Set File name
$file_temp_name = $profile_id . '_original.' . md5(time()) . 'n' . $type; //the temp file name
$fullpath = $uploaddir . "/" . $file_temp_name; // the temp file path
$file_name = $profile_id . '_temp.jpeg'; //$profile_id.'_temp.'.$type; // for the final resized image
$finalname = $profile_id . md5(time());
$fullpath_2 = "assets/images/profile_pics/" . $finalname . "n.jpg"; //for the final resized image
//Move the file to correct location
if (move_uploaded_file($ImageTempName, $uploaddir . $fullpath_2)) {
chmod($uploaddir . $fullpath_2, 0777);
}
//Check for valid uplaod
if (!$move) {
die ('File didnt upload');
} else {
$imgSrc = "assets/images/profile_pics/" . $file_name; // the image to display in crop area
$msg = "Upload Complete!"; //message to page
$src = $file_name; //the file name to post from cropping form to the resize
}
}

Personally I have used imagecreatefromjpeg
http://php.net/manual/en/function.imagecreatefromjpeg.php
Passed the temp uploaded file directly to this function.
Then this allows me to use imagescale for profile pic sizing.
http://php.net/manual/en/function.imagescale.php
Finally I find file-put-contents is a rather clean way to save the content.
http://php.net/manual/en/function.file-put-contents.php

Related

Error saving the path of an image in my database

I want to save the path of an image in my database, these images are generated with html2canvas and are saved in a directory, but when I generate them and save them in my database, a non-existent image name is generated and that is the one that stores me.
This is the code of how the image is saved in the database:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include './save.php';
$file = './images';
$route = $file. "/". $imgName;
$insert = $conexion->query("INSERT INTO images (img) VALUES ('$route')");
if ($insert) {
echo "<script>alert('successfully registered image')</script>";
}
else {
echo '<script>("Ups...Something's wrong")</script>';
}
}
This is the code that decodes the image for me and saves it in the folder:
$image = json_decode(file_get_contents("php://input"));
$image = $image->capture;
$image = str_replace("data:image/png;base64,", "", urldecode($image));
$image = base64_decode($image);
$imgName = "Image_" . uniqid() . ".png";
file_put_contents("images/$imgName", $image);

Generate thumbnail image from video in codeigniter

i want to generate the thumbnail image from the uploaded video but the problem is that the thumbnail image is not generating. The uploaded video goes to the uploads folder but at this place the image is not generating..Please look at the code, and tell me where i am wrong.
public function add_video() { // move_upload_file code
if(!empty($_FILES['video']['name'])){
$tmp_name_array = $_FILES['video']['tmp_name'];
$n_array = $_FILES['video']['name'];
$exp = explode('.', $n_array);
$newnme = date('his').rand().'.'.end($exp);
$raw_name = explode('.', $newnme);
$full_path = base_url('uploads').'/'.$newnme;
$new_path = base_url('uploads').'/';
if(move_uploaded_file($tmp_name_array, "uploads/".$newnme))
{
$full_path = base_url('uploads').'/'.$newnme;
$new_path = base_url('uploads').'/';
print_r(exec("ffmpeg -i ".$full_path." ".$new_path.$raw_name[0].".jpg"));
echo "uploaded Successfully";
}
}else{
echo "not selected any file";
}
}

PHP upload image different directory

i have a problem with uploading images into different directory.
$path = "../uploads/";
$path2 = "../uploads2/";
$imagename = $_FILES['photoimg']['name'];
$actual_image_name = $imagename;
$uploadedfile = $_FILES['photoimg']['tmp_name'];
$widthArray = array(600,240); //resize width.
foreach($widthArray as $newwidth)
{
$filename = $uploadedfile,$path,$actual_image_name,$newwidth;
//Original Image
if(move_uploaded_file($uploadedfile, $path.$actual_image_name))
{}
if(move_uploaded_file($uploadedfile, $path2.$actual_image_name))
{}
i want to upload image into uploads and uploads2 folders also?
for example width width = 600px into uploads, width = 240px into folder upload2.
what's wrong with my code?
After moving the file with move_uploaded_file it isn't available in the location stored in $uploadedfile anymore. For the second file you have to use copy function.
Please try the following:
if(move_uploaded_file($uploadedfile, $path.$actual_image_name))
{}
if(copy($path.$actual_image_name, $path2.$actual_image_name))
{}
Remove this line. I don't know for what purpose it's there.
$filename = $uploadedfile,$path,$actual_image_name,$newwidth;
To resize the uploaded image use any library to resize it then pass it.
But here is the full code to upload in different directory. But you will have to resize these two $file1 & $file2 to your expected resize file and replace the same in $file1 & $file2
To resize you can use any code suggested here
$path1 = "../uploads/";
$path2 = "../uploads2/";
$file1= $_FILES['photoimg'];
$file2= $_FILES['photoimg'];
$file1_imagename = $file1['name'];
$file2_imagename = $file2['name'];
$file1_actual_image_name = $file1_imagename;
$file2_actual_image_name = $file2_imagename;
$file1_uploadedfile = $file1['tmp_name'];
$file2_uploadedfile = $file2['tmp_name'];
$widthArray = array(600, 240); //resize width.
if (move_uploaded_file($file1_uploadedfile, $path1 . $file1_actual_image_name)) {
echo "Uploaded Successfully!";
}
if (move_uploaded_file($file2_uploadedfile, $path2 . $file2_actual_image_name)) {
echo "Uploaded Successfully!";
}

Save full URL link in database when image upload

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 ;

How to change name of uploaded file without changing extension

i'd like to change the name of uploaded file to md5(file_name).ext, where ext is extension of uploaded file. Is there any function which can help me to do it?
$filename = basename($_FILES['file']['name']);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new = md5($filename).'.'.$extension;
if (move_uploaded_file($_FILES['file']['tmp_name'], "/path/{$new}"))
{
// other code
}
Use this function to change the file name to md5 with the same extension
function convert_filename_to_md5($filename) {
$filename_parts = explode('.',$filename);
$count = count($filename_parts);
if($count> 1) {
$ext = $filename_parts[$count-1];
unset($filename_parts[$count-1]);
$filename_to_md5 = implode('.',$filename_parts);
$newName = md5($filename_to_md5). '.' . $ext ;
} else {
$newName = md5($filename);
}
return $newName;
}
<?php
$filename = $_FILES['file']['name'];
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new = rand(0000,9999);
$newfilename=$new.$filename.$extension;
if (move_uploaded_file($_FILES['file']['tmp_name'],$newfilename))
{
//advanced code
}
?>
Find below php code to get file extension and change file name
<?php
if(isset($_FILES['upload_Image']['name']) && $_FILES['upload_Image']['name']!=='') {
$ext = substr($_FILES['upload_Image']['name'], strpos($_FILES['upload_Image']['name'],'.'), strlen($_FILES['upload_Image']['name'])-1);
$imageName = time().$ext;
$normalDestination = "Photos/Orignal/" . $imageName;
move_uploaded_file($_FILES['upload_Image']['tmp_name'], $normalDestination);
}
?>
This one work
<?php
// Your file name you are uploading
$file_name = $HTTP_POST_FILES['ufile']['name'];
// random 4 digit to add to our file name
// some people use date and time in stead of random digit
$random_digit=rand(0000,9999);
//combine random digit to you file name to create new file name
//use dot (.) to combile these two variables
$new_file_name=$random_digit.$file_name;
//set where you want to store files
//in this example we keep file in folder upload
//$new_file_name = new upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif
$path= "upload/".$new_file_name;
if($ufile !=none)
{
if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path))
{
echo "Successful<BR/>";
//$new_file_name = new file name
//$HTTP_POST_FILES['ufile']['size'] = file size
//$HTTP_POST_FILES['ufile']['type'] = type of file
echo "File Name :".$new_file_name."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size']."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type']."<BR/>";
}
else
{
echo "Error";
}
}
?>

Categories