I'm trying to copy an image from a URL to my server, but it doesn't save. Below is my code
$year ='2018';
$make = 'jeep';
$model = 'grand-cherokee';
$url = 'https://www.blabla.com/images/auctions/a540c388ce3ad8a480c62212abb7a895263da16689931dc34a2f9cdd3a2c7fcf68e22b87b79f9829c398a1e324df4791549f8a2557586bae9d1c0a37166d2a79050750ce2e20138a54bb53c47d631bb60c4c2bae6320f15fe88e83c2150d111ef616d2ffc2d80db947d0942b5e16d6d744aa2696611eac9987fe21fc662bbe3ca08dbdb3abf4c0c8b81bcf721dae19560b6365cf0f3d3a0629caa3f75ed52a43fb9832';
$tmp_filename = explode('/images/auctions/', $url);
$filename = $tmp_filename[1].'.jpg';
//server path
$path = str_replace(' ', '-', strtolower(Yii::app()->basePath.'/www/storage/auction/us/'.$year.'/'.$make.'/'.$model.'/'.$filename));
$_path = pathinfo($path);
if (!file_exists($_path['dirname'])) {
mkdir($_path['dirname'], 0755, true);
}
//copy image to server
if (!is_file($path)) {
copy($url, $path);
//move_uploaded_file($url, $path);
}
The image URL in $url, doesn't have a file extension, but the image is a .jpeg
i tried both copy() and move_uploaded_file() but failed.
when i use copy() i get this error
copy(c:\xampp\htdocs\web\frontend/www/storage/auction/us/2018/jeep/grand-cherokee/a540c388ce3ad8a480c62212abb7a895263da16689931dc34a2f9cdd3a2c7fcf68e22b87b79f9829c398a1e324df4791549f8a2557586bae9d1c0a37166d2a79050750ce2e20138a54bb53c47d631bb60c4c2bae6320f15fe88e83c2150d111ef616d2ffc2d80db947d0942b5e16d6d744aa2696611eac9987fe21fc662bbe3ca08dbdb3abf4c0c8b81bcf721dae19560b6365cf0f3d3a0629caa3f75ed52a43fb9832.jpg): failed to open stream: No such file or directory
I also tried with directory 2018/jeep/grand-cherokee exist and without too.
what am is wrong here? Thanks
found the problem, Guess the filename was too long? I got this error when i tried manually saving the image from browser to desktop
a540c388ce3ad8a480c62212abb7a895263da16689931dc34a2f9cdd3a2c7fcf68e22b87b79f9829c398a1e324df4791549f8a2557586bae9d1c0a37166d2a79050750ce2e20138a54bb53c47d631bb60c4c2bae6320f15fe88e83c2150d111ef616d2ffc2d80db947d0942b5e16d6d744aa2696611eac9987fe21fc662bbe3ca08dbdb3abf4c0c8b81bcf721dae19560b6365cf0f3d3a0629caa3f75ed52a43fb9832
The File name. directory name or volume label syntax is incorrect
I renamed the file here
$url = 'https://www.blabla.com/images/auctions/a540c388ce3ad8a480c62212abb7a895263da16689931dc34a2f9cdd3a2c7fcf68e22b87b79f9829c398a1e324df4791549f8a2557586bae9d1c0a37166d2a79050750ce2e20138a54bb53c47d631bb60c4c2bae6320f15fe88e83c2150d111ef616d2ffc2d80db947d0942b5e16d6d744aa2696611eac9987fe21fc662bbe3ca08dbdb3abf4c0c8b81bcf721dae19560b6365cf0f3d3a0629caa3f75ed52a43fb9832';
// $tmp_filename = explode('/images/auctions/', $url);
//$filename = $tmp_filename[1].'.jpg';
$filename = $year.'-'.$make.'-'.$model.'.jpg';
//server path
$path = str_replace(' ', '-', strtolower(Yii::app()->basePath.'/www/storage/auction/us/'.$year.'/'.$make.'/'.$model.'/'.$filename));
and it works now.
Related
While Uploading the image in the server I got the error in codeigniter. But it works fine in local system.
A PHP Error was encountered:
Severity: Warning
Message: file_put_contents(upload/logo/1617000545.png): failed to open stream: Permission denied
Filename: models/Logo_m.php
Line Number: 41
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$imageName = time().'.png';
file_put_contents('upload/logo/'.$imageName, $data);````
Do you have check about your directory or permission?
Some problem maybe cause:
Directory Does not exists, you must create it first.
Permissions / Script does not have enough access to write files, you must verify the application could write directory and directory is writable.
Your code also doesn't validate the image content / metadata;
// $data = trim(explode(',', explode(';', $data)[1])[1]);
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
// determine absolute path
$imageDirectory = __DIR__ .'/upload/logo';
// check if string / content is an image
if (! ($imgInfo = getimagesizefromstring($data))) {
// do exit here because data is not a binary image string
throw new Exception('Data is not an image');
}
// check if image directory exist
if (!file_exists($imageDirectory)) {
mkdir($imageDirectory, 755, true);
}
if (!is_dir($imageDirectory) || !is_writable($imageDirectory)) {
throw new Exception('Could not save image. Directory is not writable.');
}
$extension = $imgInfo['mime'];
// optional to filter jpeg image
if ($extension === 'jpeg') {
$extension = 'jpg';
}
// use only time is not recommended due time is not unique, please change with random value
$baseName = time();
$imageName = $baseName . '.' . $extension;
$written = file_put_contents($imageDirectory.'/'.$imageName, $data);
I don't know if this has been asked before, please pardon in advance.
I created an image compression web app using the tinyPNG API, and it works as intended - that is users can upload an image file and it is compressed and saved in the server.
But then I create a download functionality for the user to download/save the compressed image.
On clicking the download link it throws up an error:
can’t find the file at http://localhost/var/www/html/imgtest/uploads/67403938_10219921906785196_7063388762713096192_n_1574687362.jpg.
Even though the compressed image is in the server.
Please help!!!
MY CODE:
require_once("vendor/autoload.php");
//makes PHP execute faster
set_time_limit(0);
//API key
\Tinify\setKey("API_KEY_HERE");
//Main code
if (isset($_POST['submit'])) {
//supported image formats.
$supported_image = array('image/jpg', 'image/jpeg', 'image/png');
foreach($_FILES['images']['name'] as $key=>$val){
$file_name = $_FILES['images']['name'][$key];
// get file extension
$ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
// get filename without extension
$filenamewithoutextension = pathinfo($file_name, PATHINFO_FILENAME);
if (in_array($_FILES['images']['type'][$key], $supported_image)) {
if (!file_exists(getcwd(). '/uploads')) {
$oldmask = umask(0);
mkdir(getcwd(). '/uploads', 0777, true);
umask($oldmask);
}
$filename_to_store = $filenamewithoutextension. '_' .time(). '.' .$ext;
move_uploaded_file($_FILES['images']['tmp_name'][$key], getcwd(). '/uploads/' .$filename_to_store);
$compress_file = getcwd(). '/uploads/' .$filename_to_store;
// optimize image using TinyPNG
try {
$source = \Tinify\fromFile(getcwd(). '/uploads/' .$filename_to_store);
$source->toFile(getcwd(). '/uploads/' .$filename_to_store);
//The code to show a modal for downloading the converted file.
} catch(Exception $e) {
echo $e->getMessage();
exit;
}
}
}
echo "<a href=".$compress_file." download>Download</a>";
}
?>```
The problem in your code is, that you create the link with $compress_file that contains absolute path to the file.
/var/www/html/imgtest/uploads/67403938_10219921906785196_7063388762713096192_n_1574687362.jpg
So when the link is clickend and the url is resolved in browser the result is
http://localhost/var/www/html/imgtest/uploads/67403938_10219921906785196_7063388762713096192_n_1574687362.jpg.
So if the localhost domain is pointed to /var/www/html/imgtest/ than the server is looking for the file in this path which doesn't exist:
/var/www/html/imgtest/var/www/html/imgtest/uploads/...
When you are generating the path to the compressed file you should put it's url into other variable where you wouldn't prepend the current directory.
$compress_file_url = '/uploads/' .$filename_to_store;
$compress_file = getcwd(). $compress_file_url;
Then you should use the $compress_file_url instead of $compress_file when creating a link
echo "<a href=\"$compress_file_url\" download>Download</a>";
This should work assuming your localhost domain is pointed to /var/www/html/imgtest. If your localhost domain is pointed to /var/www/html you might need to prepend $compress_file_url with /imgtest before it's used to create a link.
$compress_file_url = '/uploads/' .$filename_to_store;
$compress_file = getcwd(). $compress_file_url;
$compress_file_url = '/imgtest' . $compress_file_url;
I already given 777 permission to my images folder. Charts Table is also saving all record of image. I am going to attach table:charts structure here.
public function store(Request $request)
{
$input = $request->all();
$tradeID= Auth::user()->trade()->create($input);
if($file = $request->file('file'))
{
$name = time() . $file->getClientOriginalName();
$file->move('images', $name);
$photo = Chart::create(['file'=>$name]);
$input['photo_id'] = $photo->id;
}
$tradeID->chart()->create($input);
}
Try to change destination path from relative to absolute
public function store(Request $request)
{
$input = $request->all();
$tradeID= Auth::user()->trade()->create($input);
if($file = $request->file('file'))
{
$name = time() . $file->getClientOriginalName();
$file->move( public_path() . '/images/', $name); // absolute destination path
$photo = Chart::create(['file'=>$name]);
$input['photo_id'] = $photo->id;
}
$tradeID->chart()->create($input);
}
try this
if($file = $request->file('file'))
{
$name = time() . $file->getClientOriginalName();
$path = $file->storeAs('images', $name,'public');
$photo = Chart::create(['file'=>$name]);
$input['photo_id'] = $photo->id;
}
you can retreive the file with /storage/public/file_name or /file_name depending on where you told laravel to store the public files
You are not actually storing the file, you are actually moving a non-existent file.
What you might consider
You, most probably want to access uploaded file from public path. If so, you should store this file to particular folder in your storage directory and create a symlink to that directory in your public path.
Here's an example:
Storage::disks('public')->put($filename, $uploadedFile); // filename = 'images/imageFile.jpg'
This creates a file in your storage/app/public/images directory.
Then, you can create a symlink, laravel provide a simple command to do so.
php artisan storage:link
This creates a symlink to your public disk.
Then, you can access the image at http://your-site-server/storage/images/imageFile.jpg
Hope it helps.
$name = time().'.'. $file->getClientOriginalName(); //depends on ur requirement
$file->move(public_path('images'), $name);
Are you trying to move uploaded file or existing file ?
To move file you need to do:
File::move($oldPath, $newPath);
the old path and new path should include full path with filename (and extension)
To store an uploaded file you need to do:
Storage::disk('diskname')->put($newPath, File::get($file));
the new path is full path with filename (and extension).
disk is optional , you can store file directly with Storage::put()..
Disks are located in config/filesystems.php
The File::get($file) , $file is your input from post request $file = $request->file('file') , basically it gets contents of uploaded file.
UPD#1
Okay , you can do this:
$request->file('file')->store(public_path('images'));
Or with Storage class:
// get uploaded file
$file = $request->file('file');
// returns the original file name.
$original = $file->getClientOriginalName();
// get filename with extension like demo.php
$filename = pathinfo($original)['basename'];
// get public path to images folder
$path = public_path('images');
// concat public path with filename
$filePath = $path.'/'.$filename;
// store uploaded file to path
$store = Storage::put($filePath, File::get($file));
i am getting an error in uploading image into folder. there is an error occured during uploading that image.
my Controller Code is (cakeplus is my root folder ex: htpp://localhost/cakeplus) :
$directory = "http://".$_SERVER['HTTP_HOST'].'/cakeplus/pics';
if(!is_dir($directory)) {
mkdir($directory,0777);
}
$files_array = $this->data['Photo']['path'];
//pr($files_array); die;
if(isset($files_array['name']) && $files_array['name']!='') {
$filetype = $files_array['type'];
$filesize = $files_array['size'];
$filename = $files_array['name'];
$filetmpname = $files_array['tmp_name'];
$file_type = explode('.',$filename);
$ext_name = array_reverse($file_type);
$final_file_title = $ext_name[1];
$file_name = Inflector::slug( str_replace( ".".$ext_name[0], "" , $filename ). '_' .time() ,'-' );
$newFileName = $file_name.'.'.$ext_name[0];
move_uploaded_file($filetmpname, $directory.'/'.$newFileName);
$requirementuploadData['Photo']['path'] = $file_name;
$this->Photo->create();
$this->Photo->save($requirementuploadData,false);
}
Error(s)(Warnings) :
Warning (2): move_uploaded_file(http://localhost/cakeplus/pics/wallpaper-1433586197.png): failed to open stream: HTTP wrapper does not support writeable connections [APP\Controller\PhotosController.php, line 31]
Warning (2): move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\xampp\tmp\phpA80D.tmp' to 'http://localhost/cakeplus/pics/wallpaper-1433586197.png' [APP\Controller\Photos
Look into the CakePHP Upload plugin - it will abstract away much of the work that goes into dealing with file and image uploads.
The error you are seeing is because you cannot use move_uploaded_file() to transfer from a file path (C:\xampp\tmp\phpA80D.tmp) to an HTTP URL (http://localhost/cakeplus/pics/wallpaper-1433586197.png).
If you don't want to use the Upload plugin, and would prefer to keep working with what you already have, I would start by changing the $directory path. Something like this might be more appropriate:
$directory = WWW_ROOT . 'pics';
This will contain the path to your ./yourapp/webroot/pics directory, which is also the location of http://yourapp.com/pics.
Check out the documentation for more predefined paths.
may be folder dont have permission to write an image.
you should to use cakephp upload component.
$this->Upload->upload($file,$destination,$name);
I am working on the project which includes uploading image and video of user from iphone device. I am handling the backend with PHP. For uploading images I am getting the base64encode string and I have use following code to upload the image -
$str = $data['pictureurl']; // base64encode string
$newVar = base64_decode($str);
define('UPLOAD_DIR', 'userimages/');
$img = $str;
$date = strtotime(date("m-d-y H:i:s"));
$img = str_replace('data1:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data1 = base64_decode($img);
$file = UPLOAD_DIR . strtolower($data['firstName']).strtolower($data['lastName']). "_".$userId . '.png';
$totalpath = $path.$file;
#chmod('userimages/', 0777);
$success = file_put_contents($file, $data1);
From this code, image gets uploaded to the server in specified directory properly with .png extension. May I use the same code for uploading video making the file type .flv or .mov? I have tried it, but file gets placed in the folder with 0 bytes of data. What could be the problem? or is there any another solution to upload such file ?