uncaught exception: could not open file - php

so i'm trying to upload to uploadcare cdn and i get this error: Uncaught Exception: couldn't open file "ce3577f708f527ff570e0d21acb39c62.jpg"
$description = $_POST['uploaddesc'];
list($width,$height) = getimagesize($_FILES['uploadimage']['tmp_name']);
$extensions = array('image/jpeg','image/jpg','image/gif', 'image/png', 'image/tiff');
$move = 'uploads/';
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$extension = pathinfo($_FILES['uploadimage']['name']);
if(!$_FILES['uploadimage']['tmp_name']){
$errors[]="Please choose an image";
}
if(empty($description)){
$errors[]='Please choose a description for the image';
}
//IF IMAGE IS UPLOADED..
if($_FILES['uploadimage']['tmp_name']){
$mime = finfo_file($finfo, $_FILES['uploadimage']['tmp_name']);
// IF MIME FAILES OR GETIMAGESIZE IS NULL (meaning its no an image)
if(!getimagesize($_FILES['uploadimage']['tmp_name']) && !in_array($_FILES['uploadimage']['tmp_name'],$mime)){
$errors[]='Please choose an image';
unset($_FILES['uploadimage']['tmp_name']);
}
if(empty($errors)){
$randString = md5(time()); //encode the timestamp - returns a 32 chars long string
$fileName = $_FILES["uploadimage"]["name"]; //the original file name
$splitName = explode(".", $fileName); //split the file name by the dot
$fileExt = end($splitName); //get the file extension
$newFileName = strtolower($randString.'.'.$fileExt); //join file name and ext.
if(move_uploaded_file($_FILES['uploadimage']['tmp_name'], $move . $newFileName)){
$description = $_POST['uploaddesc'];
$user->insertArt($description, 'uploads/' . $newFileName, $user->getUsername($_SESSION['username']));
$file = $api->uploader->fromPath('uploads/' . $newFileName);
$file->store();
//throw new ErrorException('MEMORY USAGE ' . memory_get_peak_usage());
}
}
}

i have fixed it. i had to use realpath('uploads/' . $newfilename);

Related

How to upload Image or large file to temp folder before submit form in laravel

I'm using this code to upload files or images. It's working but can't upload a large file and I want to upload a file when selecting it from the local computer like the below image.
I use below PHP code in the controller.
$image = $request->file('file_upload');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
echo $new_name;
$image->move(public_path('images'), $new_name);
Try to use this code.
Change the $request->sharing_file with your field name.
You can increase the $size for image what you want, currently it is 16mb and working fine.
$myimage = $request->image;
$size = getClientSize();
if($sizes < 16777216){
$fileMimeType = explode('/', $myimage->getClientMimeType());
$fileType = $fileMimeType[0];
$originalFileName = substr($myimage->getClientOriginalName(), 0, strpos($myimage->getClientOriginalName(), "."));
$originalFileName = substr(str_replace(' ', '-', $originalFileName),0,10);
$rand = rand(9,1000);
$fileName = $rand.'-'.$originalFileName.'.'.$myimage->getClientOriginalExtension();
$upload = $values->move(public_path('images'), $fileName);
if($upload) {
$message = 'File Uploaded';
} else {
$message = "Failed to upload file";
}
}
else {
$message = 'Files size should be less than 16 MB.';
}
Try
if ($request->hasFile('file_upload')) {
$destinationPath = public_path().'/images/';
$file = $request->file_upload;
$fileName = time() . '.'.$file->clientExtension();
$file->move($destinationPath, $fileName);
$input['your_databse_table_field_name'] = $fileName;
}

How to save uploaded image to file using 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

Extension in php file

I created a page that can upload file to my database, but when a filename has (.), it doesnt save properly. For example I upload a file named imagefile.50.jpg, it just saves as image20.50
<?php
function upload_image()
{
if(isset($_FILES["user_image"]))
{
$extension = explode('.', $_FILES['user_image']['name']);
$new_name = $extension[0] . '.' . $extension[1];
$destination = './upload/' . $new_name;
move_uploaded_file($_FILES['user_image']['tmp_name'], $destination);
return $new_name;
}
}
To get the filename and extension of a file, you can use pathinfo, i.e.:
$file = "some_dir/somefile.test.php"; # $_FILES['user_image']['name']
$path_parts = pathinfo($file);
$fn = $path_parts['filename'];
$ext = $path_parts['extension'];
print $fn."\n";
print $ext;
Output:
somefile.test
php

Copy image from URL, change name and save to folder

Im about to start on a PHP script to import csv database.
The csv has a column with urls to product images.
What I need to be able to do is get the image, check what type of file it is (jpg, png etc), change the name, save the file to a folder on the server and then insert the file name into the database.
The inserting into the database bit I can do, its the renaming of the file im confused with.
Is it possible to grab the info like you would when uploading a file, for example:
Uploading a file using a file input in a html form
$_FILES['file']['name'];
or
$_FILES['file']['type'];
If downloading a file, could this be possible
$downloaded_image['name'];
or
$downloaded_image['type'];
or is that totally off the mark?
I have never done this before, and most of the answers on stackoverflow don't quite answer my question so was hoping someone could point me in the right direction on how to do this.
EDITED/UPDATED:
Would something like this work to get the file attributes...
$image_id = '123456';
$the_image = file_get_contents($downloaded_image);
$image_name = $the_image['name'];
$image_type = $the_image['type'];
$new_name = $image_id . '.' . $image_type;
$img_path = '/images/';
$save_image = file_put_contents($img_path, $new_name);
if($save_image) {
echo 'image saved';
} else {
echo 'Not Saved';
}
Hopefully im making some sense.
UPDATE: here is the script as it is (still needs tidying up)
define('CSV_PATH','E:/xampp/htdocs/aff/csv-import/');
// path where your CSV file is located
$csv_file = CSV_PATH . "infotuts.csv"; // Name of your CSV file
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
$i = 0;
while (!feof($csvfile)) {
$csv_data[] = fgets($csvfile, 1024);
$csv_array = explode(",", $csv_data[$i]);
$insert_csv = array();
$insert_csv['test_id'] = $csv_array[0];
// $insert_csv['test_aw_id'] = $csv_array[1];
// $insert_csv['test_name'] = $csv_array[2];
$image_id = $csv_array[1];
$download_image = $csv_array[2];
// Store the original filename
$original_name = basename($download_image);
// Original extension by string manipulation
$original_extension = substr($original_name, strrpos($original_name, '.')); // ".jpg"
// An array to match mime types from finfo_file() with extensions
// Use of finfo_file() is recommended if you can't trust the input
// filename's extension
$types = array('image/jpeg' => '.jpg','image/png' => '.png','image/gif' => '.gif');
// Get the file and save it
$img = file_get_contents($download_image);
$stored_name = 'images/' . $image_id . $original_extension;
if ($img) {
file_put_contents($stored_name);
// Get the filesize if needed
$size = filesize($stored_name);
// If you don't care about validating the mime type, skip all of this...
// Check the file information
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimetype = finfo_file($finfo, $stored_name);
// Lookup the type in your array to get the extension
if (isset($types[$mimetype])) {
// if the reported type doesn't match the original extension, rename the file
if ($types[$mimetype] != $original_extension) {
rename($stored_name, 'images/' . $image_id . $types[$mimetype]);
}
}
else {
// unknown type, handle accordingly...
}
finfo_close($finfo);
$query = "INSERT INTO test(test_id, test_aw_id, test_name) VALUES ('', '$image_id', '$stored_name')";
$n=mysqli_query($con, $query);
$i++;
}
else {
echo 'Could not get file';
}
}
fclose($csvfile);
By retrieving the file with file_get_contents(), you won't get any particularly useful information about its format. It carries no metadata similar to that found in $_FILES for upload.
If the image URLs are expected to be a full filename with an extension, and you trust the extension to be correct, you may use that as your type. However, finfo_file() with the FILEINFO_MIME_TYPE option will probe the file to return its mime type, as in image/jpeg or image/png.
So your workflow will be to:
Retrieve the image with file_get_contents()
Save it to your local filesystem with its new name
Call finfo_file() to retrieve its mime type
Update your database with the desired details.
Example:
// Assume this URL for $download_image from your CSV
$download_image = 'http://example.com/images/img1.jpg';
$image_id = 12345;
// Store the original filename
$original_name = basename($download_image); // "img1.jpg"
// Original extension by string manipulation
$original_extension = substr($original_name, strrpos($original_name, '.')); // ".jpg"
// An array to match mime types from finfo_file() with extensions
// Use of finfo_file() is recommended if you can't trust the input
// filename's extension
$types = array(
'image/jpeg' => '.jpg',
'image/png' => '.png',
'image/gif' => '.gif'
// Other types as needed...
);
// Get the file and save it
$img = file_get_contents($download_image);
$stored_name = 'images/' . $image_id . $original_extension;
if ($img) {
file_put_contents($stored_name, $img);
// Get the filesize if needed
$size = filesize($stored_name);
// If you don't care about validating the mime type, skip all of this...
// Check the file information
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimetype = finfo_file($finfo, $stored_name);
// Lookup the type in your array to get the extension
if (isset($types[$mimetype])) {
// if the reported type doesn't match the original extension, rename the file
if ($types[$mimetype] != $original_extension) {
rename($stored_name, 'images/' . $image_id . $types[$mimetype]);
}
}
else {
// unknown type, handle accordingly...
}
finfo_close($finfo);
// Now save all the extra info you retrieved into your database however you normally would
// $mimetype, $original_name, $original_extension, $filesize
}
else {
// Error, couldn't get file
}
If you want to get the mimetype string from the extension you already have, and aren't validating the type with finfo, you can flip the $types to swap keys with values.
if (in_array($original_extension), $types) {
$mimetype = array_flip($types)[$original_extension];
}
<?php
include_once('includes/functions.php');
define('CSV_PATH','E:/xampp/htdocs/aff/csv-import/');
$csv_file = CSV_PATH . "infotuts.csv";
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
$i = 0;
while (!feof($csvfile)) {
$csv_data[] = fgets($csvfile, 1024);
$csv_array = explode(",", $csv_data[$i]);
$insert_csv = array();
$insert_csv['test_id'] = $csv_array[0];
$insert_csv['test_aw_id'] = $csv_array[1];
$insert_csv['test_name'] = $csv_array[2];
$image_id = $insert_csv['test_aw_id'];
$download_image = $insert_csv['test_name'];
$original_name = basename($download_image);
$original_extension = substr($original_name, strrpos($original_name, '.')); // ".jpg"
$types = array('image/jpeg' => '.jpg','image/png' => '.png','image/gif' => '.gif');
$img = file_get_contents($download_image);
$stored_name = $image_id . $original_extension;
$stored_name = trim($stored_name);
if ($img) {
file_put_contents($stored_name, $img);
//$size = filesize($stored_name);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimetype = finfo_file($finfo, $stored_name);
if (isset($types[$mimetype])) {
if ($types[$mimetype] != $original_extension) {
rename($stored_name, 'E:/xampp/htdocs/aff/images/products/' . $stored_name);
}
}
else {
}
finfo_close($finfo);
$query = "INSERT INTO test(test_id, test_aw_id, test_name) VALUES ('', '$image_id', '$stored_name')";
$n=mysqli_query($con, $query);
$i++;
}
else {
echo 'Could not get file';
}
}
fclose($csvfile);
echo "File data successfully imported to database!!";
mysqli_close($con);
?>

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