File has copied successfully but condition is behaving wrong in Laravel - php

I have created a function to copy files one directory to another in Larave. For that, I've written below code, but the code is behaving wrong.
The function is returning value "1" that is "true" but the condition is behaving something wrong.
public static function copyOneToAnother($source) {
//Do Something
$destination = __DIR__."/uploads/testing_another_dir";
File::makeDirectory($destination);
return File::copyDirectory($source, $destination);
}
public function actionCopy(){
$source = __DIR__.'/my_project/project1';
$copy_status = $this->copyOneToAnother($source); //This is returning true
if($copy_status === 1){
echo "Files Copied Successfully";
}
else{
echo "There was an error";
}
}
This code always showing below results
There was an error
But files copied successfully and value of $copy_status is also 1 even it's going in else loop. I also tried using trim() and using true/false in if but didn't work for me.

You are checking data type matches then only you are displaying success message but data type there return true not 1 so
if($copy_status === 1){
echo "Files Copied Successfully";
}
if you check like below then it will show success
if($copy_status == 1){
echo "Files Copied Successfully";
}
Instead of comparing with one you can directly check like below so it will treat true
if($copy_status){
echo "Files Copied Successfully";
}
else{
echo "There was an error";
}
$a == $b
Equal TRUE if $a is equal to $b after type juggling.
$a === $b
Identical TRUE if $a is equal to $b, and they are of the same type.
Ref: http://php.net/manual/en/language.operators.comparison.php

If you are saying that $copy_status is returning true, then it can not be 1 at the same time.
=== checks for strict equality - 1 == true, but 1 !== true.
Also, you could just use
if ($copy_status) {
// do something here
}
This is essentially the same as writing if ($copy_status) == 1.
More about comparison here

Related

Why cant I check if something is not empty

I'm trying to validate if a image is uploaded or not.
But I can't figure this out since 2 hours...:
Input: ""
My Code:
$_SESSION["errorMessage"] = empty($image);
Output: 1 (true)
Then I want to check if it isnt empty:
$_SESSION["errorMessage"] = !empty($image); // Or empty($image) == false
But then The Output is nothing?!?!
Even If I try the first one out it, when it should be true, gives out: ""
Can anyone help me with this problem?
When you echo a false value, it won't echo anything. You have to tell php what to show, e.g. echo $_SESSION["errorMessage"] ? 'true' : 'false'; In your case you may want to cast it to an int: $_SESSION["errorMessage"] = (int)empty($image); You could also use var_dump to verify, i.e. var_dump( $_SESSION["errorMessage"] );
You can use the UPLOAD_ERR_NO_FILE value:
function isset_file($file) {
return (isset($file) && $file['error'] != UPLOAD_ERR_NO_FILE);
}
if(isset_file($_FILES['input_name'])) {
// It's not empty
}
Since sending $_FILES['input_name'] may throw a Notice
function isset_file($name) {
return (isset($_FILES[$name]) && $_FILES[$name]['error'] != UPLOAD_ERR_NO_FILE);
}
if(isset_file('input_name')) {
// It's not empty
}
Another example to try:
if ($_FILES['theFile']['tmp_name']!='') {
// do this, upload file
} // if no file selected to upload, file isn't uploaded.

Dynamic content, shows a 1 on each request

With my function what I have written I try thereby 2 things.
The links should be called like this http://localhost/?login=Bla, Now it is like this http://localhost/login,php?login "Bla
Next I would have asked, in my function a 1 is given after each call. I just can't figure out where this comes from, I've been sitting on this problem for a long time.
Output with the 1
This is the code with which I can call the pages
function Seite($pagename, $lay){
function Seite($pagename, $lay){
$path = "$lay/$pagename.php";
if (file_exists($path)) {
openSeite($path);
}
}
function openSeite($pageurl){
$fc = require($pageurl);
echo $fc;
}
function echopage($slug, $fade){
// $slug = ?SLUG=Seite
// $fade = Ordner des Layout
$page = isset($_GET["$slug"]) ? $_GET["$slug"] : "error";
$contente = seite($page, "$fade");
echo $contente;
}
I call the content on the index.php with
<? echopage("login", "admin/layout"); ?>
isset($_GET["$slug"]) returns a 1 because it is set (true), write a traditional conditional with the echo inside the if statement.
*Better Yet assign your output to a variable and concatenate the values accordingly.
$output = NULL;
if(isset($_GET["$slug"]){
$contente = seite($page, "$fade");
$output .= $contente;
}else{
//handle error
}
HTML:
<?=$output?><!--Output your displayed text held in the variable-->
ISSUE:
$page = isset($_GET["$slug"]) ? $_GET["$slug"] : "error";
You are essentially returning the set value, which is 1 also true.
From php manual for value: Returns TRUE if var exists and has any value other than NULL. FALSE otherwise.
You can test this by simply writing out a line of code echo isset($var); and checking the test php page. Then try defining a variable and doing the same thing. $var = "this is set"; then echo isset($var);, you will get a 1.

PHP page setting variable to command output and comparing to string

I'm creating a PHP page that uses an if statement to compare the value of a shell script to a string, but it alway seems to be false:
<?php
$output = shell_exec('/usr/sbin/genarts_server_status');
echo $output
if($output == "UP")
{
echo 'Server is up';
} else {
echo 'Server is down';
}
?>
Line 3 is simply echoing the value of the variable and that echo does correctly return "UP", but the comparison of the variable to the "UP" string returns false and therefore echoes "Server is down".
Any ideas what I am doing wrong?

Prevent internal error on false from file_get_contents

I would like to use the following to detect if a file exists, however there is a warning triggered when when this is the case. It works fine when file_get_contents does not return false.
$nothing = "http://www.google.com/bababababa.doc";
if (false === file_get_contents($nothing,0,null,0,1)) {
echo "File Not Found";
} else {
echo "File Found";
}
First, I'll assume that you only want to hide this error from your logs, because of course you have display_errors turned off on a production server.
You could just hide your errors away with the # error suppression operator, but that's a bad road to start down. Instead you want to define an error handler:
<?php
// define the custom handler that just returns true for everything
$handler = function ($err, $msg, $file, $line, $ctx) {return true;}
$nothing = "http://www.google.com/bababababa.doc";
// update the error handler for warnings, keep the old value for later
$old_handler = set_error_handler($handler, E_WARNING);
// run the code
$result = file_get_contents($nothing);
// go back to normal error handling
set_error_handler($old_handler);
if (false === $result) {
echo "File Not Found";
} else {
echo "File Found";
}

Why ajax response doesn't work?

I have a .php script like this:
$arr = array();
$arg1 = $_GET['arg1'];
$arg2 = $_GET['arg2'];
if ($arg1 !==1 && $arg2 !==0) {
$arr['msg'] = 'wrong values!';
header('Content-Type: application/json');
echo json_encode($arr);
exit();
}
$arr['msg'] = 'correct values!';
header('Content-Type: application/json');
echo json_encode($arr);
And here is my .js file:
$.ajax({
url : file.php,
type : 'GET',
data : {"arg1": 1, "arg2": 1},
dataType : 'JSON',
success : function (data) {
alert(data.msg);
}
});
As I expect, after executing those code, it should shows a alert containing this message: wrong values!. But it doesn't work, Why?
Note1: If I pass data : {"arg1": 1, "arg2": 0}, It will show a alert containing correct values! as well. Now I think the problem is that if-statement in the .php file.
Note2: The above code worked fine already. But now I updated my Xampp and after updating that problem has occurred.
More or less just putting together all the comments:
instead of $arg1...&&$arg2... use the logical-or operator
_GET contains strings (and arrays) and !== checks the data type first, hence $_GET['foo']!==1 will never be true
Because php's implicit type-juggling might consider values equal to 0 or 1 other than you'd expect, I'd suggest you keep the strict comparison (=== or !==).
You apparently want to check some numbers, so I threw intval() in and kept the strict comparison. But you could instead test if ('1'!==$_GET['arg1'] || '0'!==$_GET['arg2']).
<?php
if ( !isset($_GET['arg1'], $_GET['arg2']) ) {
$response = [
'status'=>'error',
'msg'=>'missing parameter(s)'
];
}
else {
// you could add another test like http://docs.php.net/ctype_digit here first
$arg1 = intval($_GET['arg1']);
$arg2 = intval($_GET['arg2']);
if ( 1!==$arg1 || 0!==$arg2 ) {
$response = [
'status' => '...',
'msg' => 'wrong values!'
];
}
else {
$response = [
'status' => '...',
'msg' => 'correct values!'
];
}
}
header('Content-Type: application/json');
echo json_encode($arr);
---side note---
I could make an argument for something like
$arguments = [
intval($_GET['arg1']), // maybe even 'arg1'=>intval($_GET['arg1'])
intval($_GET['arg2'])
];
if ( array(1,0)!==$arguments ) {
....but no, I just mention it ;-)
Your if statement states that arg1 must not be 1 and arg2 must not be 0.
When you pass data for arg1=1 and arg2=1 that statement will not work. Your problem is in your if statement. If you want your if statement work for each condition you should use or statement like this ||
if ($arg1 !==1 || $arg2 !==0) {//i made this condition *or* check this
$arr['msg'] = 'wrong values!';
header('Content-Type: application/json');
echo json_encode($arr);
exit();
}
You want || (or), not && (and), in your conditional. As currently written, it will return an error only if both values are incorrect.

Categories