Optimizing PHP code (trying to determine min/max/between case) - php

I know this code-bit does not conform very much to best coding practices, and was looking to improve it, any ideas?
if ($query['date_min'] != _get_date_today())
$mode_min = true;
if ($query['date_max'] != _get_date_today())
$mode_max = true;
if ($mode_max && $mode_min)
$mode = "between";
elseif ($mode_max && !$mode_min)
$mode = "max";
elseif (!$mode_max && $mode_min)
$mode = "min";
else
return;
if ($mode == "min" || $mode == "between") {
$command_min = "A";
}
if ($mode == "max" || $mode == "between") {
$command_max = "B";
}
if ($mode == "between") {
$command = $command_min . " AND " . $command_max;
} else {
if ($mode == "min")
$command = $command_min;
if ($mode == "max")
$command = $command_max;
}
echo $command;
Solution:
$mode_min = ($query['date_min'] != _get_date_today());
$mode_max = ($query['date_max'] != _get_date_today());
if ($mode_min){
$command_min = "A";
}
if ($mode_max) {
$command_max = "B";
}
if ($mode_min && $mode_max) {
$command = $command_min . " AND " . $command_max;
} else {
if ($mode_min)
$command = $command_min;
if ($mode_max)
$command = $command_max;
}

Technically your variables are undefined if the condition is not met, so I would just use:
$mod_min = ($query['date_min'] != _get_date_today());
$mod_max = ($query['date_max'] != _get_date_today());
Apart from that, why are you defining the $mode variable, do you need it somewhere else? If not, you can just use $mod_min and $mod_max in your last set of if statements.
For example:
if ($mode == "min" || $mode == "between")
seems to translate to:
if ($mod_min)
Edit: An edit of your last update:
$command_min = "A";
$command_max = "B";
if ($mode_min && $mode_max) {
$command = $command_min . " AND " . $command_max;
}
elseif ($mode_min){
$command = $command_min;
}
elseif ($mode_max) {
$command = $command_max;
} else {
return;
}

Related

Interacting with a file in PHP causes second interaction to just not happen

This is probably going to have a simple answer, but here is my problem. I am currently writing a weak permissions filesystem, I want the user to not have to do any authentication checks if the given file is empty (this is the $filedir variable). I can successfully check if this file is empty, however, if I try to read anything else (shown by file_get_contents(data.data)), it just simply will not work. There are no errors, but the condition will always evaluate as true. I have been stuck on this forever, and I'm still new to PHP, so hopefully, someone can help me out here!
Thank you in advance!
Karl
<?php
$filedir = substr(getcwd(), 0, strpos(getcwd(), "this")).'this/is/' . $_SESSION['user_name'] . '/a' . '/' . $_POST['dataName'];
if ($_POST['c'] == "true") {
$filedir = substr(getcwd(), 0, strpos(getcwd(), "this")).'this/is/a' . '/' . $_POST['dataName'];
}elseif ($_POST['c'] == "") {
// code...
}else {
$filedir = substr(getcwd(), 0, strpos(getcwd(), "this")).'this/is' . '/' . $_POST['c'] . '/a' . '/' . $_POST['dataName'];
}
**//THIS IS THE FIRST CONDITION THAT, WHEN IMPLEMENTED, CAUSES THE SECOND CONDITION TO ALWAYS EVALUATE TO TRUE FOR SOME REASON**
$pass = false;
if (readfile($filedir) == 0) {
$pass = true;
echo "check";
}else {
echo "pass";
}
if ($_POST['auth'] == "1") {
$prev = getcwd();
chdir(substr(getcwd(), 0, strpos(getcwd(), "this")) . 'this/is/adir');
$cue = file_get_contents("data.data");
// throw new \Exception("Incorrect auth token", 1);
if ($_POST['token'] == $cue) {
$_SESSION['apiauth'] == $_POST['token'];
}elseif (file_get_contents($filedir) == '') {
$_SESSION['apiauth'] == '';
}else {
throw new \Exception("Incorrect auth token", 1);
}
chdir($prev);
}elseif ($_POST['permissions'] == true) {
addLog($fn,'Permissions were changed', 'DATABASE-PERMISSIONS', null, null, 'Target: '. $_POST['dataName'] . 'Change: {Type: '.$_POST['type'].', Usertype: '.$_POST['user'].', Name: '.$_POST['name']);
if ($_POST['revoke'] == true && ($_POST['user'] != 'u' || ($_POST['user'] == 'e' || $_POST['user'] == 'a' || $_POST['user'] == 'm' || $_POST['user'] == null))) {
throw new \Exception("Cannot revoke access without proper format", 1);
}
$prev = getcwd();
chdir(substr(getcwd(), 0, strpos(getcwd(), "this")) . 'this/is/adir');
$cue = file_get_contents("data.data");
**//BELOW THIS IS THE SECOND CONDITION THAT FAILS IF THE FIRST CONDITION IS IMPLEMENTED, AND WORKS FINE IF ITS LEFT OUT**
if ($cue === $_POST['token'] || $cue === $_SESSION['apiauth'] || $pass) {
if ($_POST['type'] == 'r') {
chdir(substr(getcwd(), 0, strpos(getcwd(), "this")) . 'this/is/a/dir/path');
if ($_POST['user'] == 'e' || $_POST['user'] == 'a' || $_POST['user'] == 'm') {
$cue = fopen($_POST['dataName'].".data", "w");
fwrite($cue, '**'.$_POST['user'].'**');
fclose($cue);
}elseif ($_POST['user'] == 'u') {
$d = file_get_contents($_POST['dataName'].".secure");
if ($d == '**a**' || $d == '**e**' || $d == '**m**') {
$cue = fopen($_POST['dataName'].".data", "w");
fwrite($cue, '');
fclose($cue);
}
if ($_POST['revoke'] == true) {
$writein = str_replace($_POST['name']."||","",file_get_contents($_POST['dataName'].".secure"));
$cue = fopen($_POST['dataName'].".data", "w");
fwrite($cue, $writein);
fclose($cue);
}else {
if (strpos(file_get_contents($_POST['dataName'].".secure"), $_POST['name']) !== false) {
// throw new \Exception("User already exists in permission slot", 1);
}else{
$cue = fopen($_POST['dataName'].".data", "a");
fwrite($cue, $_POST['name'].'||');
fclose($cue);
}
}
}else {
throw new \Exception("Invalid parameter.", 1);
}
}
}else {
addLog($fn,'Permission changed was blocked due to incorrect token', 'DATABASE-PERMISSIONS', 'danger', null, 'Target: '. $_POST['dataName'] . 'Change: {Type: '.$_POST['type'].', Usertype: '.$_POST['user'].', Name: '.$_POST['name']);
throw new \Exception("Incorrect auth token", 1);
}
chdir($prev);
}
?>
From the manual
Returns the number of bytes read from the file. If an error occurs,
FALSE is returned and unless the function was called as #readfile(),
an error message is printed.
You make a weak comparison on this line
if (readfile($filedir) == 0) {
}
If the call fails false == 0 will evaluate to true, because the int value will evaluate to false. false == false is true. So use strict comparison operator === and try to figure out why the call fails anyway.
if (readfile($filedir) === 0) {
}
or use, if intended if the call succeded, and returned anything (but also 0)
if (readfile($filedir) !== false) {
}

Php-script executes in case of adding definitely 3 images, I need to make it insert data into DB even if there is only one file

Firstly, I had only one picture to submit, so that there was nothing sophisticated to accomplish, but now there could be either one, two or three images. I made my code too complicated.
The main problem is:
<div id="upload-area">
<label for="file-upload" class="custom-file-upload">
<i class="fa fa-cloud-upload"></i> Add Photo or Video
</label>
<input name="files[]" id="file-upload" accept="image/*" type="file" multiple/>
I have a submit form on the website, there is an upload area to choose multiple files, so I have an array of them.
The first my idea was to run a “for” loop through all indices, but I failed, because realized that it could have worked only if I need to send images to the DB one by one(as a sequence of records) neither as a one unite raw in the table.
That’s why I added duplicated parts of code, but with different url, image name, path and etc number.
But I understood it works properly only for 3 images chosen.
I approached to make something like this:
if ($_FILES["files"]["name"][1] === null | $_FILES["files"]["name"][1].length === 0) {
$image1 = “ “;
$url1 = “ “;
else {
$upload_path1 = "uploads/1" . $_FILES["files"]["name"][1];
$url1 = "https://bettercity.online/$upload_path1";
$image1 = $_FILES["files"]["name"][1];
$uploadedfile1 = $_FILES['files']['tmp_name'][1];
$image_type1 = $_FILES["files"]["type"][1];
}
But there is a problem with inserting those empty variables values that I am unable to solve.
The current(abysmal) code:
$upload_path0 = "uploads/0" . $_FILES["files"]["name"][0];
$url0 = "https://bettercity.online/$upload_path0";
$image0 = $_FILES["files"]["name"][0];
$uploadedfile0 = $_FILES['files']['tmp_name'][0];
$image_type = $_FILES["files"]["type"][0];
$upload_path1 = "uploads/1" . $_FILES["files"]["name"][1];
$url1 = "https://bettercity.online/$upload_path1";
$image1 = $_FILES["files"]["name"][1];
$uploadedfile1 = $_FILES['files']['tmp_name'][1];
$image_type1 = $_FILES["files"]["type"][1];
$upload_path2 = "uploads/2" . $_FILES["files"]["name"][2];
$url2 = "https://bettercity.online/$upload_path2";
$image2 = $_FILES["files"]["name"][2];
$uploadedfile2 = $_FILES['files']['tmp_name'][2];
$image_type2 = $_FILES["files"]["type"][2];
$ftp_server = " ";
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
$user = " ";
$pass = " ";
if (ftp_login($conn_id, $user, $pass))
{
if ($_FILES["files"]["error"][0] > 0)
{
echo "Return Code: " . $_FILES["files"]["error"][0] . "<br />";
}
else
{
if($image_type=='image/png' || $image_type=='image/x-png')
{
if($image_type1=='image/png' || $image_type1=='image/x-png')
{
if($image_type2=='image/png' || $image_type2=='image/x-png')
{
$src0 = imagecreatefrompng($uploadedfile0);
$src1 = imagecreatefrompng($uploadedfile1);
$src2 = imagecreatefrompng($uploadedfile2);
}
elseif($image_type2=='image/jpeg' || $image_type2=='image/jpg' || $image_type2 == 'image/pjpeg')
{
$src0 = imagecreatefrompng($uploadedfile0);
$src1 = imagecreatefrompng($uploadedfile1);
$src2 = imagecreatefromjpeg($uploadedfile2);
}
}
elseif($image_type1=='image/jpeg' || $image_type1=='image/jpg' || $image_type1 == 'image/pjpeg')
{
if($image_type2=='image/png' || $image_type2=='image/x-png')
{
$src0 = imagecreatefrompng($uploadedfile0);
$src1 = imagecreatefromjpeg($uploadedfile1);
$src2 = imagecreatefrompng($uploadedfile2);
}
elseif($image_type2=='image/jpeg' || $image_type2=='image/jpg' || $image_type2 == 'image/pjpeg')
{
$src0 = imagecreatefrompng($uploadedfile0);
$src1 = imagecreatefromjpeg($uploadedfile1);
$src2 = imagecreatefromjpeg($uploadedfile2);
}
}
}
elseif($image_type=='image/jpeg' || $image_type=='image/jpg' || $image_type == 'image/pjpeg')
{
if($image_type1=='image/png' || $image_type1=='image/x-png')
{
if($image_type2=='image/png' || $image_type2=='image/x-png')
{
$src0 = imagecreatefromjpeg($uploadedfile0);
$src1 = imagecreatefrompng($uploadedfile1);
$src2 = imagecreatefrompng($uploadedfile2);
}
elseif($image_type2=='image/jpeg' || $image_type2=='image/jpg' || $image_type2 == 'image/pjpeg')
{
$src0 = imagecreatefromjpeg($uploadedfile0);
$src1 = imagecreatefrompng($uploadedfile1);
$src2 = imagecreatefromjpeg($uploadedfile2);
}
}
elseif($image_type1=='image/jpeg' || $image_type1=='image/jpg' || $image_type1 == 'image/pjpeg')
{
if($image_type2=='image/png' || $image_type2=='image/x-png')
{
$src0 = imagecreatefromjpeg($uploadedfile0);
$src1 = imagecreatefromjpeg($uploadedfile1);
$src2 = imagecreatefrompng($uploadedfile2);
}
elseif($image_type2=='image/jpeg' || $image_type2=='image/jpg' || $image_type2 == 'image/pjpeg')
{
$src0 = imagecreatefromjpeg($uploadedfile0);
$src1 = imagecreatefromjpeg($uploadedfile1);
$src2 = imagecreatefromjpeg($uploadedfile2);
}
}
}
$new_width=768;
$new_height=500;
$image_p=imagecreatetruecolor($new_width,$new_height);
imagealphablending($image_p, false);
imagesavealpha($image_p, true);
list($width,$height)=getimagesize($uploadedfile0);
$image_p1=imagecreatetruecolor($new_width,$new_height);
imagealphablending($image_p1, false);
imagesavealpha($image_p1, true);
list($width1,$height1)=getimagesize($uploadedfile1);
$image_p2=imagecreatetruecolor($new_width,$new_height);
imagealphablending($image_p2, false);
imagesavealpha($image_p2, true);
list($width2,$height2)=getimagesize($uploadedfile2);
imagecopyresampled($image_p,$src0,0,0,0,0,$new_width,$new_height,$width,$height);
imagecopyresampled($image_p1,$src1,0,0,0,0,$new_width,$new_height,$width1,$height1);
imagecopyresampled($image_p2,$src2,0,0,0,0,$new_width,$new_height,$width2,$height2);
if(move_uploaded_file($_FILES["files"]["tmp_name"][0], $upload_path0) && move_uploaded_file($_FILES["files"]["tmp_name"][1], $upload_path1) && move_uploaded_file($_FILES["files"]["tmp_name"][2], $upload_path2))
{
if ($resp['status'] == 'OK') {
$latitude = $resp['results'][0]['geometry']['location']['lat'];
$longitude = $resp['results'][0]['geometry']['location']['lng'];
$sql = "INSERT INTO problem_data(username, name, description, mediafile, mediafile1, mediafile2, district_id, category_id, location, latitude, longitude, rating, counter, general_rating, status_id, upl_date) values('$username','$name','$description','$url0','$url1','$url2','$district_id','$category_id','$location','$latitude','$longitude', 0.0, 0, 0.0, 1, '$date')";
if(mysqli_query($con, $sql))
{
if($image_type=='image/png' || $image_type=='image/x-png'){
if($image_type1=='image/png' || $image_type1=='image/x-png'){
if($image_type2=='image/png' || $image_type2=='image/x-png'){
imagepng($image_p,$upload_path0,9) ;
imagepng($image_p1,$upload_path1,9) ;
imagepng($image_p2,$upload_path2,9) ;
}
else {
imagepng($image_p,$upload_path0,9) ;
imagepng($image_p1,$upload_path1,9) ;
imagejpeg($image_p2,$upload_path2,100);
}
}
else {
if($image_type2=='image/png' || $image_type2=='image/x-png'){
imagepng($image_p,$upload_path0,9) ;
imagejpeg($image_p1,$upload_path1,100);
imagepng($image_p2,$upload_path2,9) ;
}
else {
imagepng($image_p,$upload_path0,9) ;
imagejpeg($image_p1,$upload_path1,100);
imagejpeg($image_p2,$upload_path2,100);
}
}
}
else {
if($image_type1=='image/png' || $image_type1=='image/x-png'){
if($image_type2=='image/png' || $image_type2=='image/x-png'){
imagejpeg($image_p0,$upload_path0,100);
imagepng($image_p1,$upload_path1,9) ;
imagepng($image_p2,$upload_path2,9) ;
}
else {
imagejpeg($image_p0,$upload_path0,100);
imagepng($image_p1,$upload_path1,9) ;
imagejpeg($image_p2,$upload_path2,100);
}
}
else {
if($image_type2=='image/png' || $image_type2=='image/x-png'){
imagejpeg($image_p0,$upload_path0,100);
imagejpeg($image_p1,$upload_path1,100);
imagepng($image_p2,$upload_path2,9) ;
}
else {
imagejpeg($image_p0,$upload_path0,100);
imagejpeg($image_p1,$upload_path1,100);
imagejpeg($image_p2,$upload_path2,100);
}
}
}
}
echo 'Problem uploaded';
imagedestroy($image_p);
imagedestroy($image_p1);
imagedestroy($image_p2);
}
}
}
}

Solution for eval

I am doing custom search for table. I have three search parameters: from, to and status. I have used eval() to filter result according to received parameter. Below is my code:
$search = ($from != "" || $to != "" || $status != "" );
if ($search) {
if ($from != '') {
$condition[] = '$from == $res["from_number"]';
}
if ($to != '') {
$condition[] = '$to == $res["to_number"]';
}
if ($status != '') {
$condition[] = '$status == $log["status"]';
}
$search = "if(" . implode(' && ', $condition) . '){ return false; } else { return true; }';
}
After getting the conditions I am using eval
if (eval($search)) {
}
My problem is I don't want to use eval(). It may cause security issues. Ladder if else is not possible, it would be very lengthy. Any other solution?
e.g. If i have passed value for status then i want check like
if($status == $log["status"]) {
}
if i have passed to & from number then it should be like:
if($from == $res["from_number"] && $to == $res["to_number"]) {
}
Don't use eval - it is potentially dangerous and not recommended to use.
Your code can be like this:
$result = false;
if ($from != "" || $to != "" || $status != "") {
if ($from != '' && $from != $res["from_number"]) $result = true;
if ($to != '' && $to != $res["to_number"]) $result = true;
if ($status != '' && $status != $log["status"]) $result = true;
}
if ($result) {
// ........
}

Code executed despite false if statement

I have the following code:
if ($Type != "DEA" and $VA != "Allowed" and $VolSess != 1) {
$max_rows = max($CMSReg_num_rows);
if ($max_rows == 0) {
mail($to, $subject, $body);
header('Location: '.bloginfo('home_url').'/profile');
}
}
The problem I have is that that an email is sent despite the if-statement being false, and only an email is sent. The rest of the code is not executed, i.e. no redirect. And when I comment out the mail() function, it does not send the email.
And when I add this code:
if ($VA == "Allowed") {
echo "VA = " . $VA;
}
if ($VolSess == 1) {
echo "VolSess = " . $VolSess;
}
I get this output:
VA = Allowed VolSess = 1
So I know that the condition in the if statement is false.
AND has a different order of precedence compared to &&. So your expression does not evaluate as you expect it to.
("$Type" != "DEA" and $VA != "Allowed" and $VolSess != 1)
should be
(("$Type" != "DEA") and ($VA != "Allowed") and ($VolSess != 1))
or
("$Type" != "DEA" && $VA != "Allowed" && $VolSess != 1)
for it to work as you expect it. This is one of those tiny mistakes/bugs that's easy to overlook.
try do an else after...
elseif($VA == "Allowed"){}
Try using the WordPress wp_mail().
die; after header() and also add 302 as a second argument to the header() function.
Enable error reporting with ini_set('display_errors', true); error_reporting(-1); on top of your PHP code.
Tell us what you see after making these changes.
Try:
if ($Type != 'DEA' && $VA != 'Allowed' && $VolSess != 1)
{
$max_rows = max($CMSReg_num_rows);
if ($max_rows === 0)
{
mail($to, $subject, $body);
header('Location: ' . bloginfo('home_url') . '/profile');
}
}
EDIT
The above works, but so does the oringal question code... The problem is elsewhere.
<?php
$Type = 'foo';
$VA = 'Allowed';
$VolSess = 1;
if ($Type != 'DEA' and $VA != 'Allowed' and $VolSess != 1)
{
$max_rows = 0;
if ($max_rows === 0)
{
echo 'Orig True';
}
}
else
{
echo 'fine?';
}
if ($Type != 'DEA' && $VA != 'Allowed' && $VolSess != 1)
{
$max_rows = 0;
if ($max_rows === 0)
{
echo 'Second True';
}
}
else
{
echo 'fine?';
}
?>
Both print 'fine?' Implying your error is elsewhere in your code.

giving error msg at wrong condition

<?php
$dir = 'dir';
$exclude = array('.','..','.htaccess');
$q = (isset($_GET['q']))? strtolower($_GET['q']) : '';
$res = opendir($dir);
if (strlen($q) < 3) {
echo "Search must be longer than 3 characters.<br><br>";
} else {
if (!( ($q == "mp3") || ($q == "wav") || ($q == ""))){
while(false!== ($file = readdir($res))) {
if(strpos(strtolower($file),$q)!== false &&!in_array($file,$exclude)) {
$nicefile = str_replace(".mp3", "", "$file");
$info = pathinfo($file);
if (($info["extension"] == "mp3") || ($info["extension"] == "wav")) {
echo "<a href='http://domainname/filename.php?name=$file'>$nicefile</a>";
echo "<br>";
}elseif(!isset($errorMsg)){
$errorMsg = "ERROR: File not found.<br><br>";
}else{}
}elseif(!isset($errorMsge)){
$errorMsge = "ERROR: File not found.<br><br>";
}else{}
}
if (isset($errorMsge)){echo $errorMsge;}
else{}
if (isset($errorMsg)){echo $errorMsg;}
else{}
}else{echo"ERROR: File not found.<br><br>";}
}
closedir($res);
?>
this is like a search script and the problem is #
if(strpos(strtolower($file),$q)!== false &&!in_array($file,$exclude))
{
it shows the error msg whether there is results or file named like search query or not.
any idea how to fix that?

Categories