Search the Community
Showing results for 'detecting mobile device'.
-
Going insane. Ajax call sets session as expected but does not persist.
jtorral replied to jtorral's topic in PHP Coding Help
The problem is as follow. 1. This is some old code thats been around for ages. 2. Mobile devices have different screen sizes. 3. Setting the session of the screen size lets me manipulate the various page width and image sizes to display on a mobile device based on the width. If a device has a screen width of x I want to make sure the image is set for that screen width. with different device screens, the image can be too big or small. 4. Setting the session also let me access that stores screen size of other functions on the page like resizing pop up boxes and so on. Hope that explains it -
If you want to hire the best iOS mobile app development company in the United States to make your brand more prominent in the digital space, then Zazz is a service provider you can always count on. Even though it is not very complicated to hire top agencies or connect with the best application developers, our team has expertise in iPhone and iPad app development which makes us a reliable iOS app development team.
-
Delete Problems List in VSC
requinix replied to LeonLatex's topic in Editor Help (PhpStorm, VS Code, etc)
The "Problems" tab is a list of problems detected by the IDE and/or various extensions. You clear the list by fixing the problems, or somehow otherwise turning off the error reporting. You can hide the tab entirely through the right-click menu on the tab area, and similarly for the problems list in the status bar. -
@gizmola it would seem that the Software as a Service model would be more in line with my thinking (since I fear my code being co-opted). How is this best implemented? In simple terms, if the customer wants users to complete a form, would I just re-direct them to a form on MY server? Wouldn't that seem a bit suspicious if detected?
-
Best way to log last logged in IP address and registered IP address
requinix replied to mobbdeep's topic in PHP Coding Help
You've got three basic options for storage: a string, a number, or as binary A string is the obvious choice because human beings think of IP addresses as strings. You can support IPv4 and IPv6 easily because it's just a string. You can do exact searches because it's just a string, but CIDR-ranged searches are hard. A number is another choice, as an IP address is essentially a number. That's fine for IPv4 addresses, but the IPv6 is too large to support. Exact and CIDR searches are easy. There's also binary, which is probably the least convenient form to work with. It has the strengths of strings (variable-width) but its own disadvantages (binary data, inefficient ranged searches), as well as the strength of numbers (efficient storage) as well as their disadvantages (need to convert to/from string format). If you don't need ranged searches then use strings, if you think you need ranged searches then think again because you probably don't. Because this is one of those times where you can get lost overthinking the problem. Besides that, Don't store just the last IP address. Store all of them. Since you're dealing with user accounts you'll also have a session, and in there you can remember the IP address, and that means you can know if it changes (which would mostly mean a mobile device switching networks, but even that isn't especially common these days). Fun side effect of this is that you're more likely to think about session security, like how you should reauthenticate a user if a request comes from the "wrong" IP address... -
We are Webslavery IT Services, a freelance web designing company who specializes in web design, web development and SEO. Webuild websites that are intuitive, adaptive to different devices, and stunning in design. We enjoy browsing through numerous designs and thematic styles from different websites and products for inspiration and find the evolving state of interactive websites particularly fascinating as we try our best to emulate them. Freelance Web Designing in Hyderabad For more Details Contact : Contact No: India:+91 8897931177,+91 9030361564 Web:http://www.webslavery.com/
-
Going insane. Ajax call sets session as expected but does not persist.
gizmola replied to jtorral's topic in PHP Coding Help
I am 100% in agreement with @jodunno on this. Media Queries is the right way to handle your problem. He provided some great links to look at. I understand that working with old code bases can be challenging. One way to work your way into it is to use a sandbox like codepen or jsfiddle and make a small proof of concept version that has a subset of the overall css and some markup, and just addresses the things you want to change in the UI. Chrome dev tools have a built in way of setting the client dimensions of the browser, to simulate a particular screen size, and there are also some extensions that do the same thing and make it a little simpler. When you first open the developer tools in chrome (using inspect) the first 2 icons let you turn on/off the device toolbar. With it on, you can set the dimesions so it simulates the dimensions of a device or you can manually set the dimensions. Then move those changes over into the new code. Hopefully it wasn't a huge mess of 100 scripts with the html markup copy/pasted everywhere, but even in a case like that, you can add a header.php and footer.php and start require_once() as you remove all the duplicate code. Last but not least, this is why a lot of css frameworks going back to bootstrap got popular fast, as they alll for the most part provide support for making your markup responsive. -
what does the data look like? is there only one row of data or is there a set of rows of data? modern php no longer assumes that unquoted associative array indexes, that are not defined constants, are strings. you must use quotes around associate array indexes. if you tried the above code, did it produce php errors? do you have php's error_reporting set to E_ALL (it should always be this value) and display_errors set to ON, so that php will help you by reporting and displaying all the errors it detects?
-
Techanic Infotech is a versatile software development company renowned for its comprehensive service offerings. Specializing in web development, mobile app development, ewallet app development company, and custom software solutions, the company leverages modern technologies and agile methodologies to deliver top-notch products that align closely with client needs.With a strong emphasis on quality and client satisfaction, Techanic Infotech serves a wide array of industries including healthcare, finance, e-commerce, and education. Their solutions are tailored to address specific business challenges, showcasing their adaptability and expertise in crafting innovative software solutions.Backed by a team of seasoned developers, Techanic Infotech positions itself as a dependable partner for businesses seeking cutting-edge software development solutions. Their commitment to delivering value-driven outcomes underscores their reputation as a reliable and forward-thinking industry player.
-
What am I doing wrong with this 'php include' coding?
mac_gyver replied to Ocean_Voyager's topic in PHP Coding Help
the file system path/filename must be to where the file is located on the disk, either using a relative path (relative to the file with the include/require starting in it) or an absolute path. a leading / refers to the root of the current disk, which is doubtful where that file is located, and which will be producing a php error about a non-existent path/file. you must get php to help you by reporting and displaying all the errors it detects. you can temporarily set php's error_reporting/display_errors in your code (you will want to remove the settings when you are done learning, developing, and debugging). you can add the following immediately after the first opening <?php tag in the main file - ini_set('display_errors', '1'); error_reporting(-1); -
Hi CBG, @mac_gyver actually posted the solution that you have chosen. And i want to say that mac_gyver and maxxd are better programmers and they have more experience than i do in this field. However, i disagree with any solutions that create a bunch of if branches because every step that a program takes can really slow it down. I definitely disagree that you cannot check it all at once. Personally, i recommend using the tools in the PHP toolbox to your advantage. I would do the following and be done with it: <?php $p = 'Yes'; $d = 'No'; $c = 'No'; $o = 'No'; $pinary = [$p] === ['Yes']; $nerror = [$d, $c, $o] === ['No','No','No']; if ($p && $nerror) { echo 'error'; exit; } echo 'No errors detected'; ?> then i would unset $pinary and $nerror to spare memory (even though 100% of coders would tell you not to do that). My point, is that you can check it all at once but you could do it differently. I would define an error and simply check if it is true.
-
my usage of htmlspecialchars is to protect you from someone trying, for example, JavaScript code in place of a name. Atleast htmlspecialchars would prevent the execution of code. You shouldn't use it on a username, email address, password etc. You will instead need to employ some sort of validation, such as regex to check names and numbers. ENT_QUOTES just converts quotations ("). session_destroy: i do not know what you are creating/developing but a login/logout process will be a good idea. However, the session will be lost whenever the user closes the browser unless you are maintaining state with cookies. You could add a logout or destroy session button, which is a post to the test-sesh2.php page. Then in test-sesh2.php, detect a post with your destroy session input and implemement a session_destroy command: if isset $POST 'destroy' then session_destroy(); let us know if you need help implementing session_destroy or validating input...
-
I'm not clear on what account you have an issue with. In general, if it's anything you really care about, then take the time to set up 2 factor authentication. Emails that claim your account is locked and prompt you to re-authenticate are often Phishing attacks, where you never actually hit the site you thought it was, and for that reason, any emails like that should be ignored, not clicked on. You might want to inspect the original email and see if it was forged. Looking at the email headers and the src of any links usually tells you the story there. Pretty much all sites have now gone to informational messages if they detect changes to an account, or unusual activity. They never prompt you to "login" or to click some link. Email is unfortunately untrustworthy and all emails needs to be viewed with suspicion.
-
Hi. I have an exsisting table Bank_Reason. I want to add an extra columb 'Colour' to it. I am getting an error when I try to change it. I have done a drop table and recreate. Can any help with this extra columb please. I worked fine before. P.S. I have noticed that i was missing a (`). NEW line INSERT INTO `Bank_Reason` (`ID`, `ReasonID`, `Reason`,`Colour`) VALUES. Makes no diffrence. DROP TABLE IF EXISTS `Bank_Reason`; CREATE TABLE IF NOT EXISTS `Bank_Reason` ( `ID` int(11) NOT NULL, `ReasonID` int(11) DEFAULT NULL, `Reason` varchar(20) DEFAULT NULL, `Colour` varchar(8) DEFAULT '#000000' ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `Bank_Reason` -- INSERT INTO `Bank_Reason` (`ID`, `ReasonID`, `Reason`,Colour') VALUES (1, 0, '---SELECT','#000000'), (2, 1, 'Other',','#0000ff'), (3, 2, 'Virgin Bank','#000000'), (4, 3, '_Spare_2','#000000'), (5, 4, 'CT','#ff00ff'), (6, 5, 'Energy','#c51010'), (7, 6, 'Mobile','#27b30b'), (8, 7, 'Virgin_BB','#06b8b6'), (9, 8, 'MNOPF','#00aa00'), (10, 9, 'Water','#aa7700'), (11, 10, '@Shops','#ff0000'), (12, 11, 'Online','#7777ff'), (13, 12, 'Cash','#000000'), (14, 13, 'Pablo','#000000'), (15, 14, 'Amazon Prime','#000000'), (16, 15, 'Ebay/Paypal','#7a061c'), (17, 16, 'Argos/Store cards','#000000'), (18, 17, 'Alexa Music','#000000'), (19, 18, 'HSBC','#aa00aa'), (20, 19, 'Amazon Orders','#aa7700'), (21, 20, 'State Pension','#301de8'), (22, 21, 'Home Insurance','#000000'), (23, 22, 'Lottery','#000000'), (24, 23, 'Rent','#000000'), (25, 24, 'Private Health','#000000'), (26, 25, 'Credit card **','#000000'), (27, 26, '_Spare_1','#000000');
-
What am I doing wrong with this 'php include' coding?
mac_gyver replied to Ocean_Voyager's topic in PHP Coding Help
a bunch of points - three ... in a relative file system path is invalid. you should be learning, developing, and debugging code on a localhost development system, such xampp. do you have php's error_reporting set to E_ALL and display_errors set to ON, preferably in the php.ini on your development system, so that php will help you by reporting and displaying all the errors it detects? is the main page a .php page? what does the 'view source' of the resulting web page show in the browser? you should use 'require' for things your code must have. your goal is to produce ONE valid web page. the file that you require is not a complete web page, it is only the code/content that you want to be required at that point in the web page. you need to validate the resulting web pages at validator.w3.org all the navigation links you have shown are all the same. you should be dynamically building the web pages using a Content Management System (CMS), in which case the navigation links would be dynamically built too, based on the defined pages, instead of manually creating and managing a bunch of pages yourself. -
I fixed the wrong quote but there is still an error. When I put the code into Notepad++ Line 8 is a blank line under create table section. MySQL said: Documentation #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(3, 2, 'Virgin Bank','#000000'), (4, 3, '_Spare_2','#000000'), (5, 4, 'CT','#f' at line 8 DROP TABLE IF EXISTS `Bank_Reason`; CREATE TABLE IF NOT EXISTS `Bank_Reason` ( `ID` int(11) NOT NULL, `ReasonID` int(11) DEFAULT NULL, `Reason` varchar(20) DEFAULT NULL, `Colour` varchar(8) DEFAULT '#000000' ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `Bank_Reason` -- INSERT INTO `Bank_Reason` (`ID`, `ReasonID`, `Reason`,`Colour`) VALUES (1, 0, '---SELECT','#000000'), (2, 1, 'Other',','#0000ff'), (3, 2, 'Virgin Bank','#000000'), (4, 3, '_Spare_2','#000000'), (5, 4, 'CT','#ff00ff'), (6, 5, 'Energy','#c51010'), (7, 6, 'Mobile','#27b30b'), (8, 7, 'Virgin_BB','#06b8b6'), (9, 8, 'MNOPF','#00aa00'), (10, 9, 'Water','#aa7700'), (11, 10, '@Shops','#ff0000'), (12, 11, 'Online','#7777ff'), (13, 12, 'Cash','#000000'), (14, 13, 'Pablo','#000000'), (15, 14, 'Amazon Prime','#000000'), (16, 15, 'Ebay/Paypal','#7a061c'), (17, 16, 'Argos/Store cards','#000000'), (18, 17, 'Alexa Music','#000000'), (19, 18, 'HSBC','#aa00aa'), (20, 19, 'Amazon Orders','#aa7700'), (21, 20, 'State Pension','#301de8'), (22, 21, 'Home Insurance','#000000'), (23, 22, 'Lottery','#000000'), (24, 23, 'Rent','#000000'), (25, 24, 'Private Health','#000000'), (26, 25, 'Credit card **','#000000'), (27, 26, '_Spare_1','#000000');
-
Going insane. Ajax call sets session as expected but does not persist.
gizmola replied to jtorral's topic in PHP Coding Help
Basically what is being described to you is a race condition. You aren't going to be able to hack around it. A PHP script runs on the server, and has "page/request" scope. The client provide an HTTP request, and the server provides an HTTP response, and the connection is closed. Ajax is used to make changes to the state of a fully rendered DOM on the client. You are not going to be able to trick PHP into doing some of its work -- delaying while the client's DOM is in a partial/indeterminate state, in order for ajax to spawn another request, and then have the original PHP script resume in the way you hope it will, all so that you can get access to session variables that didn't even exist when the original HTTP request was made. I have no idea why you are trying to store some client state in a session, given that browser dimensions are dynamic, relative to the device and decisions made by the client. It's not clear what you expect to do with these dimensions, which you're getting from javascript code, but you certainly don't need to put them into a session, and you haven't made an attempt to explain what problem you are trying to solve, but this is not the way to solve whatever problem that is. If you want to actually take the time to explain the "problem to be solved" we might be able to better advise you on ways to solve it. -
Don't know if I should post this here or in the jquery forum. But here is the deal. My index.php has the following .... <?php session_start( [ 'cookie_lifetime' => 86400, ]); //session_start(); //$SID = session_id(); ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); include_once( '../gallerysoftconfig.php'); include_once( 'functions.php'); include_once( '../iconfig.php'); include_once( 'indexPreChecks.php'); include_once( 'sessionChecks.php'); include_once( 'screenDetect.php'); //print_r($_SESSION); //$xyz = $_SESSION['gs_session_screen_width']; //echo "Width: $xyz <br>"; As you can see lots commented out for testing Then the issue is in screenDetect.php And here is screenDetect.php <?php if( isset($_REQUEST['sw'] ) ) { $screenWidth = $_REQUEST['sw']; $_SESSION['gs_session_screen_width'] = $screenWidth; //$s = $_SESSION['gs_session_screen_width']; //echo "New session processed: $s"; return; } if(isset($_SESSION['gs_session_screen_width']) ) { $screenWidth = $_SESSION['gs_session_screen_width']; //echo "Session processed: $screenWidth"; return; } if(! isset($_SESSION['gs_session_screen_width']) ) { echo ' <script src="https://apis.google.com/js/platform.js" async defer></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script> <script type="text/javascript"> var screenWidth = screen.width; $.ajax({ type: "POST", url: "/screenDetect.php", data: {sw: screenWidth}, success: function() { } }); </script> '; } ?> There are some comments there that I use for validation But the story is, that the ajax call is simply getting the device screen size and calling it self with a POST. That works just fine The if( isse($_REQUEST['sw']) ) does get executed and sets the session. I have validated this by assigning the session to a variable and it does print it. I even do a print_r($_SESSION) and I see it. However, when I pickup the code in index.php, the session that was set there is no longer visible. Its like it never existed. I have tried the session_start() at the begining of screenDetect but no luck. Any idea what is going on ??? Thanks JT
-
Generate students postions based on marks scored in an exam
mac_gyver replied to sule's topic in MySQL Help
and what exactly is the problem with the last posted code? here are some points for the current code - you should use a single database extension. now that you have used the much simpler and better designed PDO extension, all your code should be updated to use the extension. you should NOT use the mysqli_real_escape_string() function, which probably doesn't have the character-set set, to match your database tables, when the connection was made, then put these pieces of data directly into the sql query statement, as this can allow sql special charters in a value to break the sql query syntax. you should use a prepared query. converting a query that has php variables being put into it into a prepared query is straight forward. if you need, someone can post a list of instructions how to do this. you should use a get method form when determining what will be displayed on a page. this is so that if someone finds a result they want to return to or share with someone, they can bookmark the URL or share the URL and be able to return to the same result. the search form should be on the same page as the result and the form should be 'sticky' and repopulate the fields, selected options, checkboxes, and radiobuttons with any existing values so that if the search doesn't find what the user expects, they can simply make changes to the search values and try again. all the search form processing code should be inside the conditional statement testing if the form has been submitted. the current code will produce a bunch of php errors and likely produce no search result and output if the page is requested without any form data. you need to trim, mainly so that you can detect if all white-space characters were entered, then validate all input data before using it. the search inputs you have shown are all 'required'. if they are not all valid, you should output error messages stating what is wrong with them and NOT run any of the query/output code. if you want to make any of these search inputs 'optional' you will need to dynamically build the WHERE part of the query and only include the terms that have search values. the use of LEFT JOIN doesn't make sense (to me). it indicates that you want to get marks data that may not have any student or school associated with it. you should just use a JOIN if you only want marks data that has school/student data. if a query doesn't match any data, you should output a message stating so, rather than outputting nothing. you need to apply htmlentities() to dynamic values being output in a html context, right before/as they are being output in order to prevent any html entities in a value from being able to break the html syntax. -
two problems - 1) you don't have php's error_reporting set to E_ALL (it should always be this value) and display_errors set to ON, preferably in the php.ini on your system, so that php will help you by reporting and displaying all the errors it detects, and 2) once you do that, you will get a php error about the 1st argument being a string instead of a datetime (Interface/immutable) object. to use date_format() you must first create a datetime object from the fetched value - $DD = new datetime($row["OrderDate"]); echo $FormattedDate = date_format($DD,'d-m-Y H:i');
-
hi im trying to make a game server page. i have found gameq files which does all the hard work i have it working and printing raw data to the page but i'd like to print them into a table this is what i have so far and it doesn't work if anyone could help id appreciate it. <?php require_once('GameQ/Autoloader.php'); $GameQ = new \GameQ\GameQ(); $GameQ->addServer([ 'type' => 'css', 'host' => '46.105.73.18:27015', ]); $results = $GameQ->process(); print_r($results); ?> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="description" content="" /> <meta name="author" content="" /> <title>Defcon Gaming</title> <link rel="icon" type="image/x-icon" href="assets/favicon.ico" /> <!-- Font Awesome icons (free version)--> <script src="https://use.fontawesome.com/releases/v6.3.0/js/all.js" crossorigin="anonymous"></script> <!-- Google fonts--> <link href="https://fonts.googleapis.com/css?family=Varela+Round" rel="stylesheet" /> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet" /> <!-- Core theme CSS (includes Bootstrap)--> <link href="css/styles.css" rel="stylesheet" /> </head> <table class="table table-striped table-dark"> <thead> <tr> <th scope="col">List</th> <th scope="col">Address</th> <th scope="col">Game Type</th> <th scope="col">Server Name</th> <th scope="col">Players</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>List</td> <td> <?php echo $results[gq_gametype]; ?> </td> <!-- how can i print the veriable to this table--> <td> <?php echo $results[gq_hostname]; ?> </td><!-- how can i print the veriable to this table--> <td> <?php echo $results[players]; ?> </td><!-- how can i print the veriable to this table--> </tr> </tr> </tbody> </table> </html> what am i doing wrong with this code?
-
I'm gusseting the posted picture is after you have submitted the form? after you set php's error_reporting to E_ALL and display_errors to ON, you should find the reason for that problem. here are a ton of coding practices that will help organize and simplify the code - the code for any page should be laid out in this general order - initialization post method form processing get method business logic - get/produce data needed to display the page html document some specific points for the posted code - use 'require' for things your code must have. include/require are not functions. the () around the path/filename don't do anything and should be left out. don't echo large amounts of static html. drop out of php mode and put the html inline. if you use php's short open-echo tag and a closing tag around a value, you can output variables in the html document using <?=$var?> don't escape double-quotes inside a php double-quoted string. simply use single-quotes inside the string. don't unnecessarily switch out of and back into php mode. just stay in php mode. don't use post method forms for navigation. use href/links. your markup is out of date. you need to validate the resulting web pages at validator.w3.org because this entire page requires the current user to be an administrator, preform the user level test once, near the top of the code and take an appropriate action if the user isn't an administrator. to get a form to submit to the same page it is on, simply leave out the entire action='...' attribute. you need to store the customer first and last names in separate columns. as a more advanced programming subject, if you have more than 2-3 form fields, you need to dynamically validate and process the form data and dynamically produce the form fields, instead of writing out code for every possible field. some points for the post method form processing code - don't attempt to detect if the submit button is set. there are cases where it won't be. instead, detect if a post method form was submitted. keep the form data as a set in a php array variable, such as $post or $data, then operate on elements in this array variable throughout the rest of the code. trim all the input data before validating it, mainly so that you can detect if all white-space characters were entered. once you do item #2 on this list, you can trim all the data using one line of code. validate all the now trimmed input data, storing user/validation errors in an array using the field name as the array index. after the end of the validation logic, if there are no errors, use the submitted form data. use a prepared query to prevent any sql special characters in value from being able to break the sql query syntax. if it seems like using the mysqli extension is overly complicated and inconsistent, it is. this would be a good time to switch to the much simpler and better designed PDO extension. if an insert/update query can produce duplicate data errors, you need to test for and handle this in the query exception handling for the query and setup a message for the user (add it to the array holding the user/validation errors) letting them know what was wrong with the data that they submitted. after using the submitted form data, if there are no errors, perform a redirect to the exact same URL of the current page to cause a get request for that page. this will prevent to browser from trying to resubmit the form data should that page get browsed back to or reloaded. to display a one-time success message, store it or a flag value in a session variable, then test for this session variable, display the message, and clear the session variable at the appropriate location in the html document. if there are errors, the code will continue on to redisplay the html document, where you will test for an display any errors, either all at once or individually adjacent to the field they correspond with, and populate the form fields with any existing data so that the user doesn't need to keep reentering values over and over. any dynamic value you output in a html context needs to have htmlentities() applied to it to help prevent cross site scripting.
-
When I click start I get this error Status change detected: stopped 16:03:16 [mysql] Error: MySQL shutdown unexpectedly. 16:03:16 [mysql] This may be due to a blocked port, missing dependencies, 16:03:16 [mysql] improper privileges, a crash, or a shutdown by another method. 16:03:16 [mysql] Press the Logs button to view error logs and check 16:03:16 [mysql] the Windows Event Viewer for more clues 16:03:16 [mysql] If you need more help, copy and post this 16:03:16 [mysql] entire log window on the forums In general, no one can figure out this PHP, as I understand it, errors pop up on their own on elementary things, is this solvable, or is there another language where this does not happen?
-
Using php to display different images based on the date
gizmola replied to Ocean_Voyager's topic in PHP Coding Help
The first thing I would note about what you have is that it should only have a single condition, because you only have one holiday. If the holiday period is not matched, you will want your default header. These are the types of tasks that you should start to see as better supported with a function. It's also a best practice not to mix your logic with markup. In other words, just have a function that returns one thing, which in your case would be the path to the correct header image. Ideally you should put this type of code into a Function. Here's an example of what you could do: <?php function getSiteHeaderImgFromDate($timeStamp=null) { // Get month and day from today [$m, $d] = explode('-', date('n-j', $timeStamp)); // Check for Christmas Holiday Range if ($m == 12 || ($m == 1 && $d <= 5)) { return 'image/site/site-header-christmas.png'; } else { return 'image/site/site-header.png'; } } Ideally, you would have a small library file of these functions, that you would require_once() at the top of your Scripts. One thing you might notice is that the function requires a $timeStamp parameter. This was done in order to make a function like this testable. If you call the PHP function date() without a timestamp parameter, it will always return the current date, making it impossible to test your condition section. You won't really know if the conditions work without modifying the function source while testing. Another alternative would be to create a unit test for this function that "mocks" the php built-in data() function, but that is a entire subject in itself I'm not going to get into right now. I'll just leave it, that there are libraries you can use like Mockery that can be useful with a problem like this. So for your code, I designed this to be testable by passing a unix timestamp which is what the date() function actually requires. If you don't pass it, it just defaults to the current timestamp. So this allows you to simulate other dates using the php mktime() function. Here are some tests of the function to validate it works. echo getSiteHeaderImgFromDate(mktime(0, 0, 0, 12, 1, 2000)) . PHP_EOL; echo getSiteHeaderImgFromDate(mktime(0, 0, 0, 1, 5, 2000)) . PHP_EOL; echo getSiteHeaderImgFromDate(mktime(0, 0, 0, 1, 6, 2000)) . PHP_EOL; echo getSiteHeaderImgFromDate() . PHP_EOL; The results are: image/site/site-header-christmas.png image/site/site-header-christmas.png image/site/site-header.png image/site/site-header.png So how SHOULD you use this function? Again, Ideally you have the function in a PHP script (along with any other useful functions you might write. One idea would be to call this script something like "site_helpers.php". For this example I'll assume you are doing this in an index.php script.... <?php require_once('site_helpers.php'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <header> <img class="header__img" src="<?= getSiteHeaderImgFromDate(); ?>"> </header> </body> </html> So hopefully, this illustrates some ideas for you: Using Functions Designing a function to be testable Collecting functions into scripts allowing re-use across different pages. Separating your Markup from PHP code. Using PHP alternative syntax/tags. You should also use it for intermingling control structures in your HTML markup, when that is needed. See https://www.php.net/manual/en/control-structures.alternative-syntax.php -
Message: Hello, I am working on a PHP project where I need to fetch mileage and location data from an API for vehicles stored in my database. The code below is meant to: Fetch an access token using the appid and login_key. Retrieve mileage and location data for each vehicle using the IMEI from the database. Update the created_jobs table with the fetched data (run KM, current KM, latitude, longitude). However, the data is not being updated correctly in the database. The issue seems to be with fetching or processing the API responses. Here’s the code I’m using: <?php // Enable error reporting and logging error_reporting(E_ALL); ini_set('display_errors', 0); ini_set('log_errors', 1); ini_set('error_log', 'php_error.log'); header('Content-Type: application/json'); // Include database connection include('db.php'); // Ensure this file contains valid DB connection details if ($mysqli->connect_error) { error_log("Database connection failed: " . $mysqli->connect_error); exit("Database connection error"); } // Function to call API function callApi($url, $headers = [], $method = 'GET', $data = null) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); if ($method === 'POST' && $data !== null) { curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); } if (!empty($headers)) { curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); } $response = curl_exec($ch); if (curl_errno($ch)) { error_log("cURL Error: " . curl_error($ch)); return null; } curl_close($ch); return json_decode($response, true); } // Function to fetch access token function getAccessToken($appid, $login_key) { $timestamp = time(); $signature = md5(md5($login_key) . $timestamp); $url = "https://open.iopgps.com/api/auth"; $data = [ "appid" => $appid, "time" => $timestamp, "signature" => $signature ]; $response = callApi($url, ["Content-Type: application/json"], 'POST', $data); if (isset($response['accessToken'])) { return $response['accessToken']; } error_log("Failed to fetch access token. API response: " . json_encode($response)); return null; } // API credentials $appid = "xyz"; $login_key = "xyz"; // Fetch access token $access_token = getAccessToken($appid, $login_key); if (!$access_token) { error_log("Failed to fetch access token"); exit("Access token error"); } // Fetch distinct vehicles from customer table $query = "SELECT DISTINCT vehicle_no, gps_imei FROM customer"; $result = $mysqli->query($query); if ($result && $result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $vehicle_no = $row['vehicle_no']; $imei = $row['gps_imei']; // Log the IMEI and Vehicle Number for debugging error_log("Processing vehicle_no: {$vehicle_no}, IMEI: {$imei}"); // Define time range for mileage API (last 1 hour) $start_time = date("Y-m-d H:i:s", strtotime("-1 hour")); // last hour dynamically $end_time = date("Y-m-d H:i:s", time()); // current time // Fetch mileage data (distance traveled) $mileage_api_url = "https://open.iopgps.com/api/device/miles?accessToken={$access_token}&startTime={$start_time}&endTime={$end_time}&imei={$imei}"; $mileage_response = callApi($mileage_api_url, ["Content-Type: application/json"]); // Log the response for mileage data error_log("Mileage API Response: " . json_encode($mileage_response)); // Fetch location data (latitude and longitude) $location_api_url = "https://open.iopgps.com/api/device/location?imei={$imei}&accessToken={$access_token}"; $location_response = callApi($location_api_url, ["Content-Type: application/json"]); // Log the response for location data error_log("Location API Response: " . json_encode($location_response)); // Validate mileage data $api_miles = 0; if (isset($mileage_response['miles']) && is_numeric($mileage_response['miles'])) { $api_miles = $mileage_response['miles']; } else { error_log("Invalid mileage data for IMEI: {$imei}. API response: " . json_encode($mileage_response)); } // Validate location data $latitude = $longitude = null; if (isset($location_response['lat']) && isset($location_response['lng'])) { $latitude = $location_response['lat']; $longitude = $location_response['lng']; } else { error_log("Invalid location data for IMEI: {$imei}. API response: " . json_encode($location_response)); } // Update the database if data is valid if ($api_miles > 0 && $latitude !== null && $longitude !== null) { $update_query = "UPDATE created_jobs SET run_km = IFNULL(run_km, 0) + ?, current_km = IFNULL(current_km, 0) + ?, latitude = ?, longitude = ? WHERE vehicle_no = ?"; $stmt = $mysqli->prepare($update_query); if ($stmt) { $stmt->bind_param("ddsss", $api_miles, $api_miles, $latitude, $longitude, $vehicle_no); $stmt->execute(); error_log("Updated vehicle_no: {$vehicle_no} | KM Added: {$api_miles} | Lat: {$latitude} | Lng: {$longitude}"); } else { error_log("Failed to prepare statement for vehicle_no {$vehicle_no}: " . $mysqli->error); } } else { error_log("Skipping update for vehicle_no {$vehicle_no} due to invalid data."); } } echo "Run KM, Current KM, and Location data updated for all matching vehicles."; } else { error_log("No vehicles found in customer table."); echo "No vehicles found."; } $mysqli->close(); ?> Issue: The API is returning data, but it’s not updating the database as expected. I'm seeing responses in the log, but the created_jobs table is not getting updated. Request: Can anyone help me identify what might be wrong with the logic, or if there's an issue with the API calls or the way I’m handling the database update? I appreciate any insights!