How to include a php file in php with condition - php

While running my code on localhost I had a problem with the include command.
Here's my code:
<?php
$res = 2; // this also can be change to any number. it is based on user input, but for simply the problem i make it to be set manually
If ($res =1,){
$open = include ("weekend.php");
}
else{
$open = include ("weekday.php");
}
echo $open;
?>
I expected the output to be weekday.php, but the output is weekend.php.
It works fine if I use $res = 1.

Besides the obvious typos (the capital I in If, the comma at the end of the condition), you're using the wrong operator. = is the assignment operator. In order to check equality, you should use the == operator:
if ($res == 1) {
// ---^
$open = include ("weekend.php");
}
else {
$open = include ("weekday.php");
}

Related

Laravel 5 Simple Comparison Fails

This should be simple but for some reason code in my if block is executing despite the fact that it resolves to false and it's making me very unhappy... My user_id in this case is 2.
$note = Notification::where("user_id",Auth::user()->id)->first();
$wall = $note->pluck('wall');
if($wall != 0)
{
//This code is executing!
}
else{
array_push($data,"Your First Time!");
//This code is not!
}
As you can see, my $wall should be zero so I don't understand why $wall != 0 runs.
Remove pluck
$note = Notification::where("user_id",Auth::user()->id)->first();
$wall = $note->wall; //This changed
if($wall != 0)
{
//This code is executing!
}
else{
array_push($data,"Your First Time!");
//This code is not!
}

Calculate Library Fine (PHP)

So, here is the question (https://www.hackerrank.com/challenges/library-fine) I am trying to solve. To solve this, I created a simple function calculateFine and set the conditions to calculate the fine. What's the problem, then? Well, when I run the code on my machine, everything seems fine, but hackerrank won't accept the code. I am new to PHP and concept of functions was a bit confusing for me, but I tried. Below is my code:
<?php
$_fp = fopen("php://stdin", "r");
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
$_a = explode(" ",fgets($_fp));
$_b = explode(" ",fgets($_fp));
// Initialising variable
$_fine = "";
// Calling Function
calculateFine($_a,$_b);
// Defining Function
function calculateFine($actualDate, $returnDate)
{
// Checking various conditions
if ($actualDate[0] <= $returnDate[0] && $actualDate[1] == $returnDate[1] && $actualDate[2] == $returnDate[2])
{
$_fine = 0;
echo $_fine;
}
elseif($actualDate[0] > $returnDate[0] && $actualDate[1] == $returnDate[1] && $actualDate[2] == $returnDate[2])
{
$_late = $actualDate[0] - $returnDate[0];
$_fine = 15*$_late;
echo $_fine;
}
elseif($actualDate[1] > $returnDate[1] && $actualDate[2] == $returnDate[2])
{
$_late = $actualDate[1] - $returnDate[1];
$_fine = 500*$_late;
echo $_fine;
}
elseif($actualDate[2] > $returnDate[2])
{
$_fine = 10000;
echo $_fine;
}
else
{
$_fine = 0;
echo $fine; // Updated (This is the undefined variable causing error )
}
}
?>
It seems there's a newline in $actualDate[2]. So if you trim it you'll get the right answer:
trim($actualDate[2])
But would be better to trim it here already:
$_a = explode(" ",trim(fgets($_fp)));
$_b = explode(" ",trim(fgets($_fp)));
I got it, sorry for the carelessness. The last echo is $fine instead of $_fine. That's why the condition was not matching with some of the test cases. Thankyou.

PHP Regular Expressions and CSV Validation

I am trying to create a CSV Checker which inserts the checked data into a Database and any unsuccessful data added to a .txt file.
I am trying to used regular expressions to validate the data I am inserting, the while loop without any validation works and inserts fine but as soon as regular expressions are used it does not work.
<?php
include_once('connection.php');
error_reporting(E_ALL);
date_default_timezone_set('Europe/London');
$date = date('d/m/y h:i:s a', time());
$filetxt = "./errors.txt";
$errors = array();
$var1 = 5;
$var2 = 1000;
$var3 = 10;
$sql = '';
if(isset($_POST["Import"]))
{
echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while(($emapData = fgetcsv($file, 10000, ",")) !==FALSE)
{
if(isset($_GET['strProductCode']))
{
$emapData[0] = $conn->real_escape_string(trim($_POST['strProductCode']));
if (!preg_match("^[a-zA-Z0-9]+$^", $_POST['strProductCode']))
{
$errors['strProductCode'];
}
}
if(isset($_GET['strProductName']))
{
$emapData[1] = $conn->real_escape_string(trim($_GET['strProductName']));
if (!preg_match("^[a-zA-Z0-9]+$^", $_POST['strProductName']))
{
$errors['strProductName'];
}
}
if(isset($_GET['strProductDesc']))
{
$emapData[2] = $conn->real_escape_string(trim($_GET['strProductDesc']));
if (!preg_match("^[a-zA-Z0-9]+$^", $_POST['strProductDesc']))
{
$errors['strProductDesc'];
}
}
if(isset($_GET['intStock']))
{
if (!preg_match("^[0-9]", $_POST['intStock']))
{
$errors['intStock'];
}
}
if(isset($_GET['intPrice']))
{
if (!preg_match("[0-9]", $_POST['intPrice']))
{
$errors['intPrice'];
}
}
if(isset($_GET['dtmDiscontinued'])){
if($emapData[6] == preg_match("[a-zA-Z]", $_POST['dtmDiscontinued']))
{
$emapData[6] = $date;
echo $date;
}else{
$emapData[6] = Null;
}
}
if(count($errors > 0))
{
// errors
$write = "$emapData[0], $emapData[1], $emapData[2], $emapData[3], $emapData[4], $emapData[5], $emapData[6]\r\n";
file_put_contents($filetxt , $write , FILE_APPEND);
}else{
// insert into Database
$sql = "INSERT INTO tblproductdata(strProductCode, strProductName, strProductDesc, intStock, intPrice, dtmAdded, dtmDiscontinued) VALUES('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]','$date','$emapData[6]')";
$res=$conn->query($sql);
}
}
fclose($file);
echo "CSV File has successfully been Imported";
echo "<br>";
echo "Any errors within the CVS Database are reported here.";
echo "<br>";
$fh = fopen($filetxt, 'r');
$theData = fread($fh, filesize($filetxt));
fclose($fh);
echo $theData;
}else{
echo "Invalid File: Please Upload a Valid CSV File";
}
header("Location: index.php");
}
?>
My knowledge of PHP is not great but this is my best attempt.
Any help would be greatly appreciated.
There are several issues in your code. Let's start with the regular expressions and your error checking:
Some of your expressions are invalid. Note that each expression needs a delimiting character at the beginng and ending of the expression. In some of your expressions (like ^[0-9]) these delimiters are missing. Please also note that using ^ as a delimiter for a regular expression is not a good choice, because the ^ character also has a special meaning in regular expressions.
This should actually cause PHP Warnings. I see that you have error_reporting enabled; you should also have a look at your display_errors setting.
As mentioned in my comment, you do not assign any values to the $errors array. The statement $errors['strProductName'] in itself does not change the array; this means that $errors will always be empty. You probably mean to do something like:
$errors['strProductName'] = TRUE;
You're actually checking count($errors > 0) where you should be checking count($errors > 0). count($errors > 0) translates to either count(TRUE) or count(FALSE) which both equal 1.
Some other notes:
Some times, you check for $_GET['strProductCode'], but then use $_POST['strProductCode'].
You do not reset the $errors array for each iteration. That means that for each line that you read, the $errors variable will still contain the errors from the previous iteration. As a result, the first invalid line will cause all following lines to be recognized as invalid, too.
You register an error when one of the parameters is of an invalid format, but not when one of them is not set at all (i.e. when isset($_POST[...]) is FALSE). Each of them should probably be sth. like this:
if (isset($_POST['strProductCode'])) {
$emapData[0] = $conn->real_escape_string(trim($_POST['strProductCode']));
if (!preg_match("^[a-zA-Z0-9]+$^", $_POST['strProductCode'])) {
$errors['strProductCode'] = TRUE;
}
} else {
$errors['strProductCode'] = TRUE;
}

php code only work if files has been changed

The variable in the session only changes if i update the file meaning:
<?php
if(isset($_GET['row']) && isset($_GET['quantity'])) {
if($_GET['quantity'] != 0) {
$_SESSION['basket'][$_GET['row']]['barcode']['quantity'] = $_GET['quantity'];
} else {
unset($_SESSION['basket'][$_GET['row']]);
}
}
?>
Changes the quantity first time and then in other tries doesn't.
If I change it to something like:
<?php
if(isset($_GET['row']) && isset($_GET['quantity'])) {
if($_GET['quantity'] != 0) {
$num = $_GET['quantity'];
$_SESSION['basket'][$_GET['row']]['barcode']['quantity'] = $num;
} else {
unset($_SESSION['basket'][$_GET['row']]);
}
}
?>
I save the file in works once and then it stops changing the quantity.
When echoing the variable in the code in shows that it's changed but in the rest of the site it doesn't. the part where it shows doesn't manipulate the variables only prints them.
It seems as if the code works only if the file's been saved and only for the first time.
Thanks in advance.

exit() Doesn't work?

I have this php script it's not inside a function
$num = mysql_num_rows($result);
if ($num == 0)
{
header("Location:index.php#captcha");//Location:#errorlogin.html");
$_POST[password]="";
exit;
}
It always seems to continue executing everything after this part regardless of $num being equal to 0 I have already tried exit("message"), die, return etc. Sorry if it's a noobish question haha
You're redirecting the page.
An example to notice from this page:
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
$_POST[password]="";
That should probably be (note the '):
$_POST['password'] = "";
The function exit() definitely stops execution when it is executed. There must be something wrong with your if condition.
In PHP multiple values "equal" to zero (if you use ==). Try var_dump($num) to see what's really in there.
exit would not working because it is has 2 dependency
A. if ($num == 0) if $num is not zero exit would not work
B. header("Location:index.php#captcha"); If your location works exit would not wort
try
$num = mysql_num_rows ( $result );
if ($num == 0) {
$_POST ['password'] = null;
header ( "Location: http://yoursite.com/index.php#captcha" ); // Location:#errorlogin.html");
exit();
}
else
{
echo "Found $num in the database";
}

Categories