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?
Related
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.
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.
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
I want to receive a POST request from a JS client with a json body (i.e. this is not form data), and save the .gigs (javascript) array to a file, after checking the .password field. This is all my code (based on Receive JSON POST with PHP)
$json_params = file_get_contents("php://input");
if (strlen($json_params) > 0 && isValidJSON($json_params)){
/* json_decode(..., true) returns an 'array', not an 'object'
* Working combination: json_decode($json_params) WITH $inp->password
*/
$inp = json_decode($json_params);
} else {
echo "could not decode POST body";
return;
}
$password = $inp->password;
// echo $password;
if ($password == "****") {
$gigs = $inp['gigs'];
// WAS $res = file_put_contents('gigs.json', json_encode($gigs), TEXT_FILE);
$res = file_put_contents('gigs.json', json_encode($gigs));
if ($res > 0) {
echo "Success";
return;
} else {
if (!$res) {
http_response_code(500);
echo "file_put_contents error:".$res;
return;
} else {
http_response_code(500);
echo "Error: saved zero data!";
return;
}
}
}
else {
// http_response_code(403); // (2)
echo "Password invalid";
return;
}
What I find is that
if I comment out the if statement and uncomment echo $password; then the right password is there
if I uncomment line 2, which I want to do, then I get back a 500 and the error logs refer an Illegal string offset 'password' in line (1) above. Without that I get back a "Success" (all for the same password).
I don't understand what is happening, nor how to get 200, 403 and 500 error messages safely.
Note
$json_params = file_get_contents("php://input");
If your scripts are running upon regular HTTP requests, passing data like it comes from HTML form, them you should consider using $_POST for your content, not php://input. If you expect JSON in request body, then I'd be fine, yet I'd also check content type for application/json.
Next:
$inp = "I never got set";
if (strlen($json_params) > 0 && isValidJSON($json_params)){
$inp = json_decode($json_params, true);
}
$password = $inp->password;
$password = $inp['password'];
This is pretty broken. First, see json_decode() arguments (2nd) -> you are decoding to array (true), not object (false), so only $password = $inp['password']; will work in your case. Also the whole code will fail when your input data is invalid as in that case $np is rubbish string, not the array you try to read later on. Use null as default value and check for that prior further use.
Next:
$res = file_put_contents('gigs.json', json_encode($gigs), FILE_TEXT);
there's no FILE_TEXT option for file_put_contents(). Nor you'd need one.
Once you correct these you'd be fine. Also print_r() and var_dump() may be the functions you wish to get familiar with for your further debugging.
In general http://php.net/ -> lookup for functions you are about to use.
I'm writing a relatively simple if statement to process the response of a web-service
The below code will output the type of data that's being returned and the value of it:
$response = $client->__getLastResponse();
echo $response;
echo gettype($response);
For a correct response, I get 'true string'
For an incorrect response, I get 'false string'
So I need an if statement to process whether it's true or false:
if($response == "true"){
echo "Logged In";
} else {
echo "Not Logged In";
}
Whatever response I get, I always receive "Not Logged In"
I've tried the === operator also, but to no avail.
Can someone help?
For a correct response, I get 'true string'
For an incorrect response, I get 'false string'
Provided that's you actual code, you have echo $response . gettype( $response ) which yields "true string", right? If so, there's a space after "true". Try to trim the response:
<?php
$response = $client->__getLastResponse();
if( strtolower( trim( $response ) ) === 'true' ) {
echo 'response is true.';
}
Apart from that, debugging is really easy using var_dump, as that will display quotes around the value and the total length of the string, making the additional space pop-up much easier to spot.