Codeigniter file_put_contents: failed to open stream: Permission denied - php

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);

Related

copy() fail to copy image from url to directory

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.

Error "Warning: file(...): failed to open stream: No such file or directory in ..." when trying to read an uploaded file

I've read other posts about this error but I couldn't find the one that suit my case.
This is the problem: after uploading a content (text file) on a specific server path (I'm using an Apache local server), I can't read it with the file() function, except when the file is contained also in the main directory (__DIR__).
This is the problematic portion of the script:
$uploaddir = __DIR__.'/cbi_files/';
if (!is_dir($uploaddir))
mkdir($uploaddir);
chmod($uploaddir, 0600);
// Recovering temporary directory
$userfile_tmp = $_FILES['cbi_file']['tmp_name'];
// Recovering originary file's name
$userfile_name = $_FILES['cbi_file']['name'];
$count=0;
$operazione = 0;
$file_caricati = array();
foreach ($_FILES['cbi_file']['name'] as $filename) {
$destination = $uploaddir;
$origin = $_FILES['cbi_file']['tmp_name'][$count];
$count++;
$destination = $destination.basename($filename);
// moving files from temporary directory to destination
$operazione = move_uploaded_file($origin, $destination);
$file_caricati[] = $filename;
}
$file_cbi = array();
$righe = array();
if (is_dir($uploaddir)) {
if ($dh = opendir($uploaddir)) {
while (($file = readdir($dh)) !== false) {
if ($file != '.' && $file != '..') {
$righe = file($file, FILE_IGNORE_NEW_LINES); // I get the error on this line
$last_row = count($righe)-1;
include(__DIR__.'/scriptCBI.php');
$file_cbi[] = array(
'nome_file' => $file,
'codice_RH' => $righe[0],
'codice_EF' => $righe[$last_row],
'recs' => $rec_array
);
}
}
closedir($dh);
}
}
I get the error if I keep the file only in $uploaddir = __DIR__'/cbi_files/', but if I keep it both in this directory and in the main directory (__DIR__) it works properly.
How's that possible?

How to fix "failed to open stream" error in Laravel project?

I want to upload image file to server. And I have failed to open stream: HTTP wrapper does not support writeable connections" error in "move_uploaded_file"
function. How can I fix it?
$image_src = $_FILES['ex_image']['tmp_name'];
$src = asset('assets/images/excavator/'.$title.'.png');
move_uploaded_file($image_src,$src);
You need to use base_path() method. This method returns the fully qualified path to the project root:
if ($request->hasFile('ex_image')) {
$destinationPath = base_path().'/assets/images/excavator/';
$file = $request->ex_image;
$fileName = $file->getClientOriginalName();
$file->move($destinationPath, $fileName);
}
and if you want to return the public directory then use:
$destinationPath = public_path().'/assets/images/excavator/';

PHP file not uploading to localhost

I've set up an XAMPP server and trying to upload image files using a custom admin page. The page works fine when I set it up on a online server running ubuntu.
But when trying the same script in localhost gives me the following error.
Warning : move_upload_file(../img/products/fw000001.jpg) : failed to open stream. No such file or directory in C:\xampp\htdocs\OBS\store\kish\bin\functions.php on line 64
Here is the file upload part of functions.php
function upload_image($image,$code)
{
define("UPLOAD_DIR", "../img/products/");
if (!empty($image)) {
$myFile = $image;
if ($myFile["error"] !== UPLOAD_ERR_OK) {
return null;
}
//check if the file is an image
$fileType = exif_imagetype($_FILES["image"]["tmp_name"]);
$allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
if (!in_array($fileType, $allowed)) {
exit();
}
// ensure a safe filename
$name = $myFile["name"];
$parts = pathinfo($name);
$extension = $parts["extension"];
$savename = $code . "." . $extension;
// don't overwrite an existing file
$i = 0;
if(file_exists(UPLOAD_DIR . $savename)) {
unlink(UPLOAD_DIR . $savename);
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $savename);
if (!$success) {
exit();
}
else
{
return $savename;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
}
}
I'm not pretty sure about directory separator. Directory separator is represent with (/) on Linux based OS. Widows is using ( \ ) for directory separator. So, please change this line and tested it.
define("UPLOAD_DIR", "../img/products/");
to
define("UPLOAD_DIR", "..".DIRECTORY_SEPARATOR."img".DIRECTORY_SEPARATOR."products".DIRECTORY_SEPARATOR.");
Change this line
// preserve file from temporary directory
$success = move_uploaded_file($_FILES["image"]["tmp_name"],UPLOAD_DIR . $savename);

failed to open stream: No such file or directory ,permission issue

I just starting upload file with the script in my localhost,
but every time I want to upload file I giving an error:
Warning: chmod() [function.chmod]: No such file or directory in /Applications/XAMPP/xamppfiles/htdocs/admin/upload.php on line 5
Warning: chmod() [function.chmod]: No such file or directory in /Applications/XAMPP/xamppfiles/htdocs/admin/upload.php on line 6
I guess the problem with permission and path but I don't know how to solve it,
my code:
<?php
define("UPLOAD_DIR",realpath(dirname(__FILE__)).'/uploads' );
// set proper permissions on the new file
chmod(realpath(dirname(__FILE__)).'/uploads', 0777);
chmod(realpath(dirname(__FILE__)).'/uploads/'.$name, 0777);
if (!empty($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
}
?>
chmod(realpath(dirname(__FILE__)).'/uploads', 0777);
chmod(realpath(dirname(__FILE__)).'/uploads/'.$name, 0777);

Categories