Why after this functions file_put_contents() line of code not executed? - php

i have created one function to upload image using web services.
$image_url=time().$img_name;
$path=$_SERVER['DOCUMENT_ROOT'].'/img';
$image_url_src=$path."/".$image_url;
$current = file_get_contents($image_url_src);
$current = base64_decode($img_url);
$res=file_put_contents($image_url_src,$current);
chmod($image_url_src, 0777);
if($res===true)
{
$folder_img_url1="http://www.example.com/img/".$image_url;
$auth_error=array("img_url" => $folder_img_url1);
return json_encode($auth_error);
}
Everything is working properly.. only problem is why not returning value after this line of code file_put_contents($image_url_src,$current);
if i return any value before file_put_contents function than it works but after calling file_put_contents() after that not return works so why?
ANY HELP WOULD BE APPRECIATED

There is problem with permission of folder
First give permission
<?php
chmod($image_url_src, 0777);
if (file_put_contents($image_url_src,$current)!== false) {
{
$folder_img_url1="http://www.example.com/img/".$image_url;
$auth_error=array("img_url" => $folder_img_url1);
return json_encode($auth_error);
}
This function returns the number of bytes that were written to the
file, or FALSE on failure. Meaning: file_put_contents will never
return TRUE. It will return false however, so if you were insistent on
using a boolean value then you would need to use:

This Code is works for me...
$image_url=time().$img_name;
$path=$_SERVER['DOCUMENT_ROOT'].'/img';
$image_url_src=$path."/".$image_url;
//$current = file_get_contents($image_url_src); //this line of code is no need because of this not returning value..because it gives me an error.
$current = base64_decode($img_url);
$res=file_put_contents($image_url_src,$current);
//chmod($image_url_src, 0777); if will remove than also its works
if($res===true)
{
$folder_img_url1="http://www.example.com/img/".$image_url;
$auth_error=array("img_url" => $folder_img_url1);
return json_encode($auth_error);
}
Thank you for your time..

Related

How to Check file exists in Laravel

I have a Laravel Controller Function file_fetch()
public function file_fetch(Request $request) {
$file = request('routename');
$destinationPath = public_path('/folder/'.$file);
if(!File::exists($destinationPath)){
$content = File::get($destinationPath);
return view('filefetch', compact('file','content'));
}
else {
return redirect('/')->witherrormessage('NO such File Exists');
}
}
This works if i check for file public/folder/app/index.html and if i check for public/newfolder (newfolder doesnt exist) and hence it executes else function and redirects with error message, but if i search for public/folder/app/ I havent specified the file name, but the directory exists, hence the if(!File::exists($destinationPath)) function is getting executed!
i want to check just and files inside the directory and even if the directory exists, if file is not present, throw a error message, saying file doesnt exists.
add one more additional condition to check given path is file but not a directory
public function file_fetch(Request $request) {
$file = request('routename');
$destinationPath = public_path('/folder/'.$file);
if(!File::exists($destinationPath) && !is_dir($destinationPath)){
$content = File::get($destinationPath);
return view('filefetch', compact('file','content'));
}
else {
return redirect('/')->witherrormessage('NO such File Exists');
}
}
You can probably fix your code by validating the routename input such that it will never be empty (and have a certain file extension maybe?)
, which is nice to do anyhow.
If that fails, you can try File::isDirectory($dir) which basically calls is_dir(...).
Note that it might give you more control on your storage solution if you use the Storage::disk('public') functionalities from Laravel. The API is a bit different but there's a wide range of probabilities associated with it. Read more about that here: https://laravel.com/docs/8.x/filesystem#introduction.
If you in different/multiple buckets.
//Do not forget to import
use Illuminate\Support\Facades\Storage;
if (Storage::disk('s3.bucketname')->exists("image1.png")) {
}

Check if the text file was empty

I'd like to know how to check if a text file is empty or not. It means that there is no text even some space, i.e. it was blank
function keyRemain($path)
{
$ambil = file_get_contents("data/$path/keywords.txt");
$kw = explode(",", $ambil);
if (count($kw) > 1) {
return false;
} else {
return true;
}
}
You have to check the empty function along with trim
function keyRemain($path)
{
$ambil = trim(file_get_contents("data/$path/keywords.txt"));
var_dump($ambil); // check the output here
if(!empty($ambil)) {
return false;
} else {
return true;
}
}
Maybe this was not the answer, just the another way to check the file. Before this was happend, the code appear instead the class. After i cut it and move it outside of the class it work perfectly without any errors.
file_get_contents() will read the whole file while filesize() uses stat() to detirmine the file size. Use filesize(), it should consume less disk I/O.
That's the answer found here, on stack...
You can also (on same link there's this answer):
clearstatcache();
if(filesize($path_to_your_file)) {
// your file is not empty
}

code for "delete full directory" returns warning

I have folder, his name is "1", in this folder is 2 folders: "big_images" and "small_images"
I want delete folder "1" and his content, this is code:
function removeFullDir ($dir) {
$content = glob($dir."/*");
foreach ($content as $file) {
if (is_dir($file)) {
removeFullDir ($file);
}
else {
unlink($file);
}
}
rmdir($dir);
}
removeFullDir("1");
in localhost (XAMPP server, php version 5.4.4) this code works good. in remote server this code also works, but returns warning:
Warning: Invalid argument supplied for foreach()
in remote server, php version is 5.2.42
please tell me, why obtain I this warning?
This happens because glob does not return an array, which means that based on the documentation it must return false. This can happen when there is an error, but it can also happen when the directory happens to be empty:
Returns an array containing the matched files/directories, an empty
array if no file matched or FALSE on error.
Note: On some systems it is impossible to distinguish between empty match and an error.
To prevent the notice just guard against it:
function removeFullDir ($dir) {
$content = glob($dir."/*");
if(!$content) {
return;
}
// ...
}
One possible reason could be open_basedir restriction which means that glob() returns false and it will error at the foreach loop as $content is not an array, so you could check like:
//before foreach
if(is_array($content) && count($content) > 0) {

Warning (2): mkdir() [function.mkdir]: No such file or directory

Hi i recently faced this problem but was able to fix it. Actually spelling mistake in path. I want to know how to handle these error properly. i.e my program should continue executing and should safely return a false if mkdir fails. This is my code
try
{
foreach($folders as $folder)
{
$path = $path.'/'.$folder;
if(!file_exists($path))
{
if(!(mkdir($path)))
{
return false;
}
}
}
return true;
}
catch (Exception $e){
return false;
}
I just want if mkdir is not able to create it. It should return a false and the execution should continue
EDIT: Here is updated code based on community feedback. But still no proper answer to my question
if(!file_exists($newfolder))
{
if(mkdir($newfolder,0755,true))
{
return true;
}
}
Are you looking for setting the recursive flag to true?
<?php
// Desired folder structure
$structure = './depth1/depth2/depth3/';
// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.
if (!mkdir($structure, 0, true)) {
die('Failed to create folders...');
}
// ...
?>
The function appears to not be recursive. You will have to make the entire directory tree, down to your directory that you want to create.
Read here. Like sarnold said, just set the recursive argument to true.
Take a look at this sample, it might be what you are looking for.
http://www.php.net/manual/en/function.mkdir.php#92844

unlisted reserved word?

I ran into a very strange behaviour in some of our PHP code today. We have a class for dealing with files. It's something like this:
class AFile {
//usual constructor, set and get functions, etc.
//...
public function save() {
//do some validation
//...
if($this->upload()) { //save the file to disk
$this->update_db(); //never reached this line
}
}
private function upload() {
//save the file to disk
//...
return ($success) ? true : false;
}
}
It looked pretty normal to us, but the $this->upload() function never returned anything but NULL. We checked that the correct function was running. We echoed out its return value before it returned. We tried only returning a true value or even a string. Everything was checking out right. But $this->upload still evaluated to NULL. Also, there was nothing in the logs and ERROR_ALL is on.
In exasperation we changed the function name to foo_upload. All of a sudden everything worked. "upload" is not in the list of PHP reserved words. Anyone have any thoughts why a class function named "upload" would fail?
Make sure the return statement at the end of the upload method is the only return statement in that method.
One way to get null when "calling" upload would be if you had this (trying to access an inexisting property) :
if($a = $this->upload) { // => NULL
$this->update_db(); //never reached this line
}
var_dump($a);
instead of this (from OP) (trying to call an existing method):
if($a = $this->upload()) { // => true or false
$this->update_db(); //never reached this line
}
var_dump($a);
Did you check you didn't forget the () ?
If it's not this, try with error_reporting set to E_ALL, and displaying the errors :
ini_set('display_errors', true);
error_reporting(E_ALL);
(you said "ERROR_ALL is on", so not sure it's what you meant)

Categories