Check if the text file was empty - php

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
}

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")) {
}

PHP 7.2 Automatically enforcing callback prior to first byte transmission to Client

PHP 7.2 :
Is there a way to enforce "automatically" calling of a php function prior to the first byte that is sent out to the client?
(HTML Tags or anything)
Eg: songs.php:
// Please ignore spelling mistakes, and work on concept alone.
require_once('sessionSetup.php');
require_once('setup_Pre_HTML_Tag_Transmission_Enforcer.php');
// The above has a function called: doMyHTMLTags();
doMyStuff(); // Setups, validations
doMoreStuff();
doHTMLContentDisplay();
// I need to execute doMyHTMLTags(), if and when any of the functions starts sending out displayable text.
Example: If doMoreStuff does a DIE('No resources'); or if doMyStuff does a { echo 'unexpected issue'; exit; }, I still need mydoMyHTMLTags() to be executed.
Any help would be appreciated.
Didn't try it, but maybe ob_start would do the trick:
ob_start(
function($buffer) {
// nothing was produced
if (strlen($buffer) === 0) {
return false;
}
// prepend our string
return doMyHTMLTags() . $buffer;
}
);
doMyStuff(); // Setups, validations
doMoreStuff();
doHTMLContentDisplay();
If doMyHTMLTags() doesn't return string, but it is printing it to the browser, you can try this (but it will always call doMyHTMLTags):
// get our string from output
ob_start();
doMyHTMLTags();
$my_html_tags = ob_get_clean();
ob_start(
function($buffer) use ($my_html_tags) {
// nothing was produced
if (strlen($buffer) === 0) {
return $buffer;
}
// prepend our string
return $my_html_tags . $buffer;
}
);
doMyStuff(); // Setups, validations
doMoreStuff();
doHTMLContentDisplay();

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

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..

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

Restrict allowed file upload types PHP

Right now I have a function which takes my uploaded file, checks the extension, and if it matches an array of valid extensions it's processed. It's a contact list importer.
What I need to figure out is how to be sure that file (in this case a .csv) is actually what it says it is (ex. not an excel file that just got renamed as a .csv).
Our servers run PHP 5.2.13
Here's the current validation function I have
public static function validateExtension($file_name,$ext_array) {
$extension = strtolower(strrchr($file_name,"."));
$valid_extension="FALSE";
if (!$file_name) {
return false;
} else {
if (!$ext_array) {
return true;
} else {
foreach ($ext_array as $value) {
$first_char = substr($value,0,1);
if ($first_char <> ".") {
$extensions[] = ".".strtolower($value);
}
else {
$extensions[] = strtolower($value);
}
}
foreach ($extensions as $value) {
if ($value == $extension) {
$valid_extension = "TRUE";
}
}
if ($valid_extension==="TRUE") {
return true;
} else {
return false;
}
}
}
}
EDIT: I'm now trying to do
exec('file -ir '.$myFile)
When I run this command in terminal I'm given a usable response. When I run the same command through php, I'm given something different. Any ideas why? I've tried it with exec, passthru, shell_exec. And the server does not have safe mode running.
Forget extension checking, it's not reliable enough.
Also, I think traditional MIME magic sniffing will fail here, because there is no usable header (This is just my guess, though.)
In this specific case, I'd say it's feasible to take a quick peek at the contents, for example read the first ten lines or so. If they are all no longer than x bytes, and each line contains the same number of semicolons (or whatever your CSV parser takes as separators), it's a CSV file.

Categories