Warning / Error for syntax with strtotime and date - php

I have just migrated a website to a new host. Not sure what software was used at the previous host, but assuming it was Apache with PHP. I am now using WAMP server( Apache 2.4.4 and PHP 5.4.16 ). The site is built on the Codeigniter framework.
I am getting two errors:
Message: strtotime() expects parameter 1 to be string, object given
Message: date() expects parameter 2 to be long, string given
They report its because of these lines:
<?=date("d.m - H:i", utf8_encode(strtotime($job->DateEnd))); ?>
This is not the only line giving this error, there is a total of 151 hits in 37 files just for "strtotime". Am no PHP coder, but this seem to be my last challenge after spending 3 days getting this site back up!
If any other code is needed, tell me and ill try to find it. I just didnt think it would fit to put every line with the search result of "strtotime" and "date" in here.
////////////////////////////////////////////////////////////////////////////////
EDIT (after 3 hours, more info) :
I put in the var_dump function right after that other line, and it showed this:
object(DateTime)#23 (3) { ["date"]=> string(19) "2014-01-08 23:59:00"["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" }
I think I found the code where $job gets set.
function job_info() {
$project = "";
$job_arranger = "";
$project_arranger = "";
$customer = "";
$contact = "";
$delivery_address = "";
$human_resources = "";
$vehicle_resources = "";
$job = $this->job->get_job_data($this->uri->segment(3));
if($job->IdUser_Arranger){
$job_arranger = $this->address->get_user_data($job->IdUser_Arranger);
}
if($job->IdProject){
$project = $this->job->get_project_data($job->IdProject);
}
if(is_object($project)) {
if($project->IdUser_Arranger) {
$project_arranger = $this->address->get_user_data($project->IdUser_Arranger);
}
if($project->IdAddress_Customer) {
$customer = $this->address->get_address_data($project->IdAddress_Customer);
}
if($project->IdContact_Customer) {
$contact = $this->address->get_contact_data($project->IdContact_Customer);
}
}
if($job->IdAddress_Delivery){
$delivery_address = $this->address->get_address_data($job->IdAddress_Delivery);
}
$human_resources = $this->job->get_job_human_resources($this->uri->segment(3));
$vehicle_resources = $this->job->get_job_vehicle_resources($this->uri->segment(3));
$data['job'] = $job;
$data['project'] = $project;
$data['job_arranger'] = $job_arranger;
$data['project_arranger'] = $project_arranger;
$data['customer'] = $customer;
$data['contact'] = $contact;
$data['delivery_address'] = $delivery_address;
$data['human_resources'] = $human_resources;
$data['vehicle_resources'] = $vehicle_resources;
$this->load->view('jobs/job_info', $data);
}
}
I am a total newbie on PHP, so even finding where $job gets set is hard for me to understand.
I am guessing the error occurs because we changed to a new SQL Datbase Server, and the dates are handled differently?

I believe the data assigned to $job->DateEnd is an object. Either create a function to retrieve the required data from it and return it as a string (this means changing a lot of code on a lot of places) or change the way $job->DateEnd is filled (this means changing a single key piece in your code).
I would opt for the latter and fight the problem at it's source!
Good luck!

Related

Using Dynamic Variable Names to Call Static Variable in PHP

I am trying to implement a logging library which would fetch the current debug level from the environment the application runs in:
23 $level = $_SERVER['DEBUG_LEVEL'];
24 $handler = new StreamHandler('/var/log/php/php.log', Logger::${$level});
When I do this, the code fails with the error:
A valid variable name starts with a letter or underscore,followed by any number of letters, numbers, or underscores at line 24.
How would I use a specific Logger:: level in this way?
UPDATE:
I have tried having $level = "INFO" and changing ${$level} to $$level. None of these changes helped.
However, replacing the line 24 with $handler = new StreamHandler('/var/log/php/php.log', Logger::INFO); and the code compiles and runs as expected.
The variable itself is declared here
PHP Version => 5.6.99-hhvm
So the answer was to use a function for a constant lookup:
$handler = new StreamHandler('/var/log/php/php.log', constant("Monolog\Logger::" . $level));
<?php
class Logger {
const MY = 1;
}
$lookingfor = 'MY';
// approach 1
$value1 = (new ReflectionClass('Logger'))->getConstants()[$lookingfor];
// approach 2
$value2 = constant("Logger::" . $lookingfor);
echo "$value1|$value2";
?>
Result: "1|1"

Undefined index when calculating age from an inputted birthdate

I am new in this site, and i found some questions that are connected to my system error but unfortunately they can't fix the error. I am creating an offline web-based information system for my capstone project and I don't understand why P_Bday is undefined.. Here is my code
This is my code for inputting Birthdate:
input type="text" id = "P_Bday" name = "P_Bday" class="form-control" data-inputmask="'alias': 'dd/mm/yyyy'" data-mask placeholder="dd/mm/yyyy" required
And here's my code for calculating age:
function ageCalculator($dob){
if(!empty($dob)){
$birthdate = new DateTime($dob);
$today = new DateTime('today');
$age = $birthdate->diff($today)->y;
return $age;
}
else{
return 0;
}
}
$dob = $_POST["P_Bday"];
And I call my function here, where it should display the calculated age depending on the inputted birthdate:
input type='text' name = 'P_Age' id='disabledTextInput' class='form-control' value='".ageCalculator($dob)."' readonly
Every time I ran my code it says:
Notice: Undefined index: P_Bday in
C:\xampp\htdocs\PISGDH\recordclerk\RecordEntry\addPatient.php on line
47
If the line $dob = $_POST["P_Bday"]; is being run on the page before anything is sent via POST, then $_POST[foo] is invalid.
Change the line to:
if(isset($_POST["P_Bday"])) $dob = $_POST["P_Bday"];
else $dob = null;
Or:
$dob = isset($_POST["P_Bday"]) ? $_POST["P_Bday"] : null;
An Undefined index error is pretty simple to debug. You start at the file mentioned in the error message C:\xampp\htdocs\PISGDH\recordclerk\RecordEntry\addPatient.php and go to the line mentioned in the error message line 47 and find the undefined index in question on that line P_Bday and know with absolute certainty that up to this point in your code you have not defined that index for that variable. You can work your way backwards through the code to try and figure out your mistake. The mistake can be a typo (you used the wrong case/variable name) or it can be that you just forgot to initialize the variable properly.
The best way to avoid undefined variable/index errors is to initialize always and initialize early. In the few cases where you cannot be sure that variables are properly initialized (for example with $_POST/$_GET or other external variables under control of client input) you want to use isset to avoid the error and that way you can coalesce null values or write logic that prevents the code from continuing with an uninitialized value in case of user error.
Example
if (!isset($_POST['P_Bday'])) {
die("You forgot to fill out your birthday!");
} else {
echo "Yay!";
}
Some good initialization techniques with $_POST/$_GET
A good best practice for "initialize always and initialize early" when dealing with user input is to setup a default set of values for the expected input from your form and initialize from that in order not to fall into this trap.
Example
$defaultValues = [
'P_Bday' => null,
'Option1' => 'default',
'Option2' => 1,
];
/* Let's say the user only supplied Option1 */
$_POST = ['Option1' => 'foo'];
/* This makes sure we still have the other index initialized */
$inputValues = array_intersect_key($_POST, $defaultValues) + $defaultValues;
/**
* Now you can pass around $inputValues safely knowing all expected values
* are always going to be initialized without having to do isset() everywhere
*/
doSomething(Array $inputValues) {
if (!$inputValues['P_Bday']) { // notice no isset() check is necessary
throw new Exception("You didn't give a birthday!!!");
}
return (new DateTime)->diff(new DateTime($inputValues['P_Bday']))->y;
}
You are declaring the variable $dob after calling function. You have to declare your variable before function call and also use conditional statement like following:
Please write your code as follows:
if(isset($_POST["P_Bday"])){
$dob = $_POST["P_Bday"];
} else {
$dob ="";
}
function ageCalculator($dob){
if(!empty($dob)){
$birthdate = new DateTime($dob);
$today = new DateTime('today');
$age = $birthdate->diff($today)->y;
return $age;
}
else{
return 0;
}
}

PHP error on testing server

I have a bit of PHP code that works fine on my production server but not on my test server. Here is the code:
function callProcedure0(&$connection, $procname, $dofunction)
{
mysqli_multi_query($connection, "CALL " . $procname . "();");
$first_result = 1;
do
{
$query_result = mysqli_store_result($connection);
if ($first_result)
{
$dofunction($query_result);
$first_result = 0;
}
if ($query_result)
{
mysqli_free_result($query_result);
}
$query_result = NULL;
} while(mysqli_next_result($connection));
}
...
function doGenres($in_result)
{
global $genre_array, $game_array, $genre_order_array;
$genre_count = 1;
// foreach is necessary when retrieving values since gaps may appear in the primary key
while ($genre_row = mysqli_fetch_row($in_result)) // line 81 is here!
{
$genre_array[] = $genre_row[0];
$genre_order_array[$genre_row[1] - 1] = $genre_count;
$game_array[] = [[],[]];
$genre_count += 1;
}
}
...
callProcedure0($con, "get_genres_front", doGenres); // line 138 is here!
The "get_genres_front" bit refers to a stored procedure on my database. Here are the errors:
Notice: Use of undefined constant doGenres - assumed 'doGenres' in /opt/lampp/htdocs/keyboard/keyboard.php on line 138
Again, there are no problems on the production server which is using Apache 2.2.23, MySQL 5.1.73-cll, PHP 5.4.26. The test server where things are broken is running Apache 2.4.10, MySQL 5.6.21, PHP 5.5.19.
Did something change in recent software versions? Thanks.
[edit]
This is not a duplicate question. I'm worried about the first error. I already know what to do about the second error which I have deleted.
The code you have posted is wrong, you must pass function name as string and then use call_user_func to invoke this function.
In your callProcedure0 function change
$dofunction($query_result);
to
call_user_func($dofunction, $query_result);
And then call it with the function name as string like this
callProcedure0($con, "get_genres_front", "doGenres");
The above code could work also with invoking the function with
$dofunction($query_result);
on some php versions, but the line where you pass the function name it should be string, otherwise PHP assumes it is a constant.

How to invoke the demo url using VinceG php-first-data-api

I am trying to integrate First Data e4 Gateway using PHP. I downloaded the VinceG/php-first-data-api PHP First Data Service API class. The code comes with some examples.
I have my Terminal ID (API_LOGIN) and Password (32 character string).
What confuses me is that when I use one of the examples, I don't know how to tell the class that I want to use the demo url, not the production url.
The class comes with two constants:
const LIVE_API_URL = 'https://api.globalgatewaye4.firstdata.com/transaction/';
const TEST_API_URL = 'https://api.demo.globalgatewaye4.firstdata.com/transaction/';
In the First Data console, when I generated my password, it said to use the v12 api, /transaction/v12, so I changed the protected $apiVersion = 'v12';
All I want to do is write my first development transaction using First Data e4. I have yet to get any kind of response. Obviously I need a lot of hand holding to get started.
When I set up a website to use BalancedPayments, they have a support forum that's pretty good, and I was able to get that running fairly quickly. First Data has a lot of documentation, but for some reason not much of it has good PHP examples.
My hope is that some expert has already mastered the VinceG/php-first-data-api, and can help me write one script that works.
Here's the pre-auth code I'm using, that invokes the FirstData class:
// Pre Auth Transaction Type
define("API_LOGIN", "B123456-01");
define("API_KEY", "xxxxxxxxxxyyyyyyyyyyyyzzzzzzzzzz");
$data = array();
$data['type'] = "00";
$data['number'] = "4111111111111111";
$data['name'] = "Cyrus Vance";
$data['exp'] = "0618";
$data['amount'] = "100.00";
$data['zip'] = "33333";
$data['cvv'] = "123";
$data['address'] = "1111 OCEAN BLVD MIAMI FL";
$orderId = "0001";
require_once("FirstData.php");
$firstData = new FirstData(API_LOGIN, API_KEY, true);
// Charge
$firstData->setTransactionType(FirstData::TRAN_PREAUTH);
$firstData->setCreditCardType($data['type'])
->setCreditCardNumber($data['number'])
->setCreditCardName($data['name'])
->setCreditCardExpiration($data['exp'])
->setAmount($data['amount'])
->setReferenceNumber($orderId);
if($data['zip']) {
$firstData->setCreditCardZipCode($data['zip']);
}
if($data['cvv']) {
$firstData->setCreditCardVerification($data['cvv']);
}
if($data['address']) {
$firstData->setCreditCardAddress($data['address']);
}
$firstData->process();
// Check
if($firstData->isError()) {
echo "!!!";
// there was an error
} else {
echo "###";
// transaction passed
}
My number one problem was that I had not created (applied for, with instant approval) a
demo account on First Data. I didn't realize this was a separate thing on First Data. On Balanced Payments, for instance, you have one account, and you can run your script on a test url with test values.
From the Administration panel, click "Terminals", then your Gateway number on the ECOMM row (will look something like AH1234-03), then you have to click "Generate" on password save it to your personal notes), then click UPDATE.
Now replace your parameter values in your test scripts. I use a variable assignment block that looks something like this:
define("API_LOGIN", "AH1234-05"); //fake
define("API_KEY", "44p7797xxx790098z1z2n6f270ys1z0x"); //fake
$data = array();
$data['type'] = "03";
$data['number'] = "4111111111111111";
$data['name'] = "Cyrus Vancce";
$data['exp'] = "0618";
$data['amount'] = "100.00";
$data['zip'] = "33320";
$data['cvv'] = "123";
$data['address'] = "1234 N OCEAN BLVD MIAMI BEACH FL";
$orderId = "0001";
require_once("FirstData.php");
$firstData = new FirstData(API_LOGIN, API_KEY, true);
at the end of the VinceG test scripts, I output my gateway response with a print_r, like this:
$firstData->process();
// Check
if($firstData->isError()) {
echo "!!!";
// there was an error
} else {
echo "###";
// transaction passed
}
echo "<pre>";
print_r($firstData);

Php-ews: creating contact birthday's event

I am trying to add a contact in Exchange, using the php-ews and the following code:
$request = new EWSType_CreateItemType();
$request->SendMeetingInvitations = 'SendToNone';
$contact = new EWSType_ContactItemType();
$contact->GivenName = $updates['name'];
$contact->Surname = $updates['surname'];
if($updates['email'] != ""){
$email = new EWSType_EmailAddressDictionaryEntryType();
$email->Key = new EWSType_EmailAddressKeyType();
$email->Key->_ = EWSType_EmailAddressKeyType::EMAIL_ADDRESS_1;
$email->_ = $updates['email'];
// set the email
$contact->EmailAddresses = new EWSType_EmailAddressDictionaryType();
$contact->EmailAddresses->Entry[] = $email;
}
$contact->CompanyName = $updates['companyname'];
$contact->JobTitle = $updates['jobtitle'];
$contact->Birthday = $updates['birthday'];
$request->Items->Contact[] = $contact;
$response = $this->ews->CreateItem($request);
Where $updates is an array of strings I have as a parameter.
(I skipped the includes, tell me if you need them.)
Now, the contact gets created and everything works, but the birthday event does not get created automatically in my calendar.
So, I would like to know if there's a simple way to have this done, except the obvious (non-elegant) way of creating it manually.
Thank you in advance,
Riccardo
Could solve this using DateTime in the right format as expected in the comments.
$contact->Birthday = (new DateTime($updates['birthday']))->format(DATE_W3C);
https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/time-zones-and-ews-in-exchange
The time zone specified in the value of dateTime elements can take three forms. You can read all the details in XML Schema Part 2: Datatypes Second Edition, but to paraphrase:
Universal Coordinated Time (UTC): Specified by 'Z'. For example, 2014-06-06T19:00:00.000Z
Specific time zone: Specified by '+' or '-' followed by hours and minutes. For example, 2014-06-06T19:00:00.000-08:00
No time zone: Specified by the absence of any time zone. For example, 2014-06-06T19:00:00.000

Categories