Why cant I check if something is not empty - php

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.

Related

File has copied successfully but condition is behaving wrong in Laravel

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

Checking if SESSION value

I want to check session data. The value of $_SESSION['yatidak'] is 'Tidak', but i can't check the condition. Why? Please see the code
$yt = $_SESSION['yatidak'];
echo $yt;
// output : Tidak
if ($yt=='Tidak') {
echo 'Tidak';
}else{
echo 'Iya';
}
// output : Iya
Echo should be :
// TidakTidak
But the result is :
// TidakIYa
The actual process is you have to do is,
session_start(); //at the very first line of the page
//Check the session value direct to the string and use trim if some white spaces are there should be removed and also use `===` which match type and data both
if (trim($_SESSION['yatidak']) === "Tidak") {
echo 'Tidak';
}else{
echo 'Iya';
}
// output sould be: Tidak
Please try this:
if ( ($yt = $_SESSION['yatidak']) == 'Tidak') {
echo 'Tidak';
}else{
echo 'Iya';
}
If that works, for adaptation of your code, make sure the $_SESSION['yatidak'] is not modified between the assignation and the verification.

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.

Check if specific input file is empty

In my form I have 3 input fields for file upload:
<input type=file name="cover_image">
<input type=file name="image1">
<input type=file name="image2">
How can I check if cover_image is empty - no file is put for upload?
You can check by using the size field on the $_FILES array like so:
if ($_FILES['cover_image']['error'] == 4 || ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0))
{
// cover_image is empty (and not an error), or no file was uploaded
}
(I also check error here because it may be 0 if something went wrong (ie. a file was selected, but there's no data received). I wouldn't use name for this check since that can be overridden). error with a value of 4 is UPLOAD_ERR_NO_FILE, so we can check for that too.
Method 1
if($_FILES['cover_image']['name'] == "") {
// No file was selected for upload, your (re)action goes here
}
Method 2
if($_FILES['cover_image']['size'] == 0) {
// No file was selected for upload, your (re)action goes here
}
You can check if there is a value, and if the image is valid by doing the following:
if(empty($_FILES['cover_image']['tmp_name']) || !is_uploaded_file($_FILES['cover_image']['tmp_name']))
{
// Handle no image here...
}
if (empty($_FILES['cover_image']['name']))
simple :
if($_FILES['cover_image']['error'] > 0)
// cover_image is empty
check after the form is posted the following
$_FILES["cover_image"]["size"]==0
if (!$_FILES['image']['size'][0] == 0){ //}
if( ($_POST) && (!empty($_POST['cover_image'])) ) //verifies if post exists and cover_image is not empty
{
//execute whatever code you want
}
if(!empty($_FILES)) { // code if not uploaded } else { // code if uploaded }
$_FILES is an associative POST method array, if You want to check anything about $_FILES You must take into account the index... I tried a lot of suggested options, and the only method that worked for me, was when I included an index in my verification method.
$_FILES['Your_File']['name'][0];
So bye doing this:
if(empty($_FILES['Your_File']['name'][0])){
print('this thing is empty');
}else{
print('Something, something, something');
}
There's nothing like good old experimentation and lots of reading.
if($_FILES['img_name']['name']!=""){
echo "File Present";
}else{
echo "Empty file";
}
if ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0)
{
// Code comes here
}
This thing works for me........
<input type="file" class="custom-file-input" id="imagefile" name="imagefile[]" multiple lang="en">
<input type="hidden" name="hidden_imagefile[]" value="<?=$row[2]; ?>" class="form-control border-input" >
if($_FILES['imagefile']['name'] == '')
{
$img = $_POST['hidden_imagefile'];
}
else{
$img = '';
$uploadFolder = 'uploads/gallery/';
foreach ($_FILES['imagefile']['tmp_name'] as $key => $image) {
$imageTmpName = time() .$_FILES['imagefile']['tmp_name'][$key];
$imageName = time() .$_FILES['imagefile']['name'][$key];
$img .= $imageName.',';
$result = move_uploaded_file($imageTmpName, $uploadFolder.$img);
}
}
if ($_FILES['cover_image']['error'] == 4){
// the user did not choose any file
}else{
// the user chose a file to be uploaded
}
This will work
if ($_FILES['cover_image']['size'] == 0 && $_FILES['cover_image']['error'] == 0)
// checking if file is selected and not an error
{
// file is not selected and it is not an error
}
UPDATED:
Use this method:
First check if 'cover_image' key exists in $_FILES then check other file errors
if (in_array('cover_image', array_keys($_FILES) && $_FILES['cover_image']['error'] == 0) {
// TODO: write your code
} else {
// return error
}

Statements in php

if($getstatus->num_rows != 0 && $getstatusarr = $getstatus->fetch_assoc() && $getstatusarr["Type"] != $data["type"])
echo "error"
else
...
first code will not work, to make works this way, see Nin's post
Is it possible to make the code easily?
Also I can do it like this:
if($getstatus->num_rows != 0)
$getstatusarr = $getstatus->fetch_assoc();
if($getstatusarr["Type"] != $data["type"]) {
echo "error"
$error = true;
}
if(!$error) {
...
}
by ellipsis I have too many lines of code :)
added:
also I can do in this way:
if($getstatus->num_rows != 0) {
$getstatusarr = $getstatus->fetch_assoc();
if($getstatusarr["Type"] != $data["type"]) {
echo "error";
goto skip;
}
}
... // some code which I need not to execute if $getstatusarr["Type"] != $data["type"] are true
skip:
// another code which will execute in all cases
Well, don't use goto: :)
Whether you put all the if's on one line or on several lines is mostly a personal preference.
Too many lines with if will make the code harder to read but putting it all on one line also makes it difficult to read and difficult to debug (error on line 12 can mean many things then). If you're using a debugger like xdebug or Zend debug then having multiple lines to step over is also easier.
So find a way in between this.
I would do it like this, since then you also check if fetch_assoc() returned a result:
if($getstatus->num_rows != 0 && $getstatusarr = $getstatus->fetch_assoc())
if($getstatusarr["Type"] != $data["type"]) {
echo "error"
$error = true;
}
if(!$error) {
...
}
From my point of view is always best to unwrap statements and clean the code as much as you can, maybe someone later on will have to read what you did and he will have a hard time doing that.
Also you cannot assign new variables in a if statement like that:
$error = false;
if($getstatus->num_rows)
$getstatusarr = $getstatus->fetch_assoc();
if($getstatusarr["Type"] != $data["type"]) {
$error = array('type' => 'invalid type');
}
}
if($error) {
// do something with $error array
}

Categories