Jump to content

Psycho

Moderators
  • Posts

    12,146
  • Joined

  • Last visited

  • Days Won

    127

Everything posted by Psycho

  1. Try putting this bit of debugging code in your script right before your if() statement. What does it produce when you run the script? if(!isset($_SESSION)) { echo "Session was not started yet"; } else { echo "Session data:<br>"; echo "<pre>".print_r($_SESSION, true)."</pre>"; }
  2. You really need to analyze the source data to identify the different data and types of issues that can exist in order to determine the appropriate solution. For example, the solution @Barand provided would be acceptable if: 1) The only issues are missing closing tags 2) None of the "data" contains a greater than sign If there are other types of issues or if data can contain the < symbol then a different solution is in order.
  3. To add to @requinix's response, the communication to the database would be between the PHP server and the database server. The client should have no idea about how the connection is made. However, if you have "holes" in your application that allows the users to infiltrate your server-side code, then all bets are off. Unfortunately, the guidance on not creating those holes is an expansive subject. A forum is great for asking abut specific aspects, but for the big picture I would suggest looking for training and/or guides on the subject.
  4. If you are submitting your form to the same page that form is on, it is typically good practice to put the form processing logic at the top of the page. That way if you need to show the results of the new data or show form processing errors you can generate that within the content of the page. I have not run your code, but I notice that the JavaScript that is called from within the action parameter of the form returns false at the end of the script. If you return false within the action parameter of a firm, then the form is never submitted. That may be your problem.
  5. To expand on @Barand's response, how you implement it depends on "how" you want the result to be returned. Are you just wanting a True/False based whether it is a multi-dimensional array, do you want the number of sub-arrays, or what?
  6. Taking a quick look at the source page to be scraped, the page appears to be specifically built to prevent scraping. Specifically, the content (i.e. the winning numbers) is loaded externally and populated on the page dynamically. It doesn't mean it can't be done, but it certainly won't be as trivial as it would seem.
  7. One significant problem with your request is you started out by saying it was a multi-dimensional array when it is , in fact, a flat array. But, your responses have been far from illustrative. Understand that you are very close to the problem and KNOW what is in your head. So, while you think a statement is perfectly obvious, to others it is greek. In any case, if you have an array that you want to "split" into "chunks" of an arbitrary size, PHP has a built-in function to do that: array_chunk() //Input data $outputFile = "output.csv"; $itemsPerLine = 3; $hexCodes = array("ff00ff", "ff00cc", "ff0099", "ff0066", "ff0033", "ff0000", "ff3300", "ff6600", "ff9900", "ffcc00", "ffff00", "ccff00", "99ff00", "66ff00", "33ff00", "00ff00", "00ff33", "00ff66", "00ff99", "00ffcc", "00ffff", "00ccff", "0099ff", "0066ff", "0033ff", "0000ff", "3300ff", "6600ff", "9900ff", "cc00ff", "9900ff", "6600ff", "3300ff", "0000ff", "0033ff", "0066ff", "0099ff", "00ccff", "00ffff", "00ffcc", "00ff99", "00ff66", "00ff33", "00ff00", "33ff00", "66ff00", "99ff00", "ccff00", "ffff00", "ffcc00", "ff9900", "ff6600", "ff3300", "ff0000", "ff0033", "ff0066", "ff0099", "ff00cc", "ff00ff"); //Open file for writing $fileHandle = fopen($outputFile, 'w'); //Split the array into chunks and write each chunk to the file //with a comma separator and a line feed character foreach (array_chunk($hexCodes, $itemsPerLine) as $line) { fwrite($fileHandle, implode(',', $line) . "\n"); } //Close the file fclose($fileHandle); Here is the output ff00ff,ff00cc,ff0099 ff0066,ff0033,ff0000 ff3300,ff6600,ff9900 ffcc00,ffff00,ccff00 99ff00,66ff00,33ff00 00ff00,00ff33,00ff66 00ff99,00ffcc,00ffff 00ccff,0099ff,0066ff 0033ff,0000ff,3300ff 6600ff,9900ff,cc00ff 9900ff,6600ff,3300ff 0000ff,0033ff,0066ff 0099ff,00ccff,00ffff 00ffcc,00ff99,00ff66 00ff33,00ff00,33ff00 66ff00,99ff00,ccff00 ffff00,ffcc00,ff9900 ff6600,ff3300,ff0000 ff0033,ff0066,ff0099 ff00cc,ff00ff EDIT: Or if you want the quote marks and spacing, replace with this line fwrite($fileHandle, '"' . implode('", "', $line) . "\"\n");
  8. 5.5 (i.e. 5:30) * 60 (minutes) * 60 (seconds) = 19800 I assume the 0 represent the first element of the array of timezone within the +5:30 UTC offset - 'Asia/Colombo'. Further, I expect you will ALWAYS get the first timezone corresponding to the UTC offset (as a default) because there is no way that an actual timezone can be specified in the string value you are using. '+05:30' => array ( 0 => 'Asia/Colombo', 1 => 'Asia/Kolkata', ),
  9. Look at the code examples on that page. The examples first create a datetime object with a specific timezone and then use gettimezone to retrieve the timezone that was previously set. A string such as "2021-05-06T13:48:19.2064951+05:30" has only the offset from UTC time - there is no timezone identifier. So, there is no way to programmatically determine the correct timezone out of the ones that share that offset.
  10. No clue. I think this is a JavaScript problem, not a PHP problem. I see the following code with references to "toggle" <a style="text-decoration: none;color: #000;" title="View Details" data-toggle="collapse" data-target="#products-details<?php echo $drow['order_id']; ?>"> <i class="nc-icon nc-minimal-down" onclick="changeToggleIcon(this)"></i> </a> But, those are tags within nothing in them to be displayed to the user. Further the actual javascript functions are not in the above code. If this is indeed a javascript problem, then you shoudl post the HTML that is generated by the PHP code and be sure to include any javascript functions that are called by that code.
  11. Here is my suggestion: Limit the size of the images you will accept Do an initial check on the extension and MIME type of the file and refuse anything that is not what you expect Use getimagesize() to verify it is an image. Resize/recreate the image. This will remove some/most malicious code. Change the name of the image Set the folder(s) where you store the images so files cannot be executed Don't allow direct access to images. E.g. when displaying the images on a page use something like <image src="getimage.php?id=5"> and create the script getimage.php to find the image based on the id (or whatever parameters you define) and pass the image contents back to the browser to be displayed. This way the malicious user won't even know how to access the file he uploaded.
  12. No. There are lossless and lossy image compression formats. Both use different methods of storing the data. A RAW image format is one form of lossless image format that has distinct data for every single pixel along with it's color. That is why they are huge in storage space. A gif and jpg (typically) are lossy formats (substitute some fidelity to create small file sizes) but work very differently. A gif has a color palet that can only hold 256 colors. It then defines each pixel in the gif by those colors. I suspect it does some other calculations such as define the pixel at index 1, 1 then also sets a repeat number. E.g. if the first 20 pixels are all the same color, it only has to define the color of the first pixel and then another value for the repeater. A JPG allows for 16 million colors but it does it's compression using more mathematical processes. For example, it may shift the color of a pixel slightly in order to make the compression more efficient. What that really means is to verify the image before saving/using it. You can only do so much validation of the image before uploading it. Once it is initially uploaded to the $_FILES array, you an run whatever validations, modifications on them and THEN save them however you choose. I think the problem you are running into is that you are reading different bits and pieces of information, but not understanding the info or WHY you should do those things. It is possible to have a legitimate image that contains malicious code. And, depending on how you use the images on your site, you could potentially risk exposing your users. So, while you should be doing things to ensure what the user provided has a legitimate image extension and PHP can tell it is an image file, a best practice is to recreate the image to remove any potentially malicious content in the image. Here is an article that explains how these vulnerabilities exist: https://asdqwedev.medium.com/remote-image-upload-leads-to-rce-inject-malicious-code-to-php-gd-image-90e1e8b2aada
  13. Your table with events has a start and end date. How are you wanting the data displayed in the calendar - only an entry on the start date? Also, can there be multiple events on the same date? The answer to those questions will probably dictate how I would do it. I think the easiest approach would be to query all the events for the given month at the beginning of the function and put them into an array. Then when outputting the TD for any given day, check if there are any events for the day - if so, include them in the output. I thought your code was hard to read/work with, so I modified it quite a bit <?php /*MAKES THE CONNECTION*/ include 'config.php'; $conn = mysqli_connect($servername, $username, $password, $dbname); // CHECK CONNECTION if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } /*DRAWS CALENDAR*/ function draw_calendar($month, $year, $conn) { //Create timestamp for the 1st of the month $firstDayTimestamp = mktime(0,0,0,$month,1,$year); //Offset the starting date number to add empty days before the 1st of month $dayNo = -1 * date('w', $firstDayTimestamp) +1; $daysInMonth = date('t', $firstDayTimestamp); //Get the events for the current month $sql = "SELECT DAY(start_day) as day, id, name, phone, item, start_day, end_day, start_time, end_time FROM $tablename WHERE YEAR(start_day) = $year AND MONTH(start_day) = $month"; $result = $conn->query($sql); //Put results into an array $events = array(); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { $events[$row["day"]][] = $row; } } //Start the calendar table $calendar = '<table cellpadding="0" cellspacing="0" class="calendar" border="1">'; //Create the calendar headings $headings = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'); $calendar.= "<tr class=\"calendar-row\">\n"; foreach($headings as $heading) { $calendar.= "\t<td class=\"calendar-day-head\">{$heading}</td>\n"; } $calendar.= "</tr>\n\n"; //Create each week in the calendar while($dayNo <= $daysInMonth) { $calendar.= "<tr class=\"calendar-row\">\n"; //Create each date for the week for($dow=0; $dow<7; $dow++) { //Check if the $dayNo is within the selected month if($dayNo<1 or $dayNo>$daysInMonth) { $calendar .= "\t<td class=\"calendar-day-np\"> </td>\n"; } else { //Code to create content for the given day $calendar .= "\t<td class=\"calendar-day\">"; $calendar .= "{$dayNo}"; //Add any events here if(isset($events[$dayNo])) { //Create outpout for each event on the current day foreach($events[$dayNo] as $eventAry) { $calendar .= "<div>{$eventAry['name']}</div>"; } } $calendar .= "</td>\n"; } //Increment the date $dayNo++; } $calendar.= "</tr>\n"; } //Close the calendar table $calendar.= '</table>'; return $calendar; } ?> <html> <body> <?php echo draw_calendar(1, 2021, $conn); ?> </body> </html>
  14. I guess I'm still missing something. A user is on the "backoffice" page and they perform some action where you want to display a set of results in a new page "frontoffice" - is that correct? If the "frontoffice" page is opened from the "backoffice" page, then you can set a target on the "frontoffice" page. Then whenever the page is opened from "backoffice" it will replace the contents in the window that "frontoffice" was loaded in. FYI: You can use javascript in one window/tab to control another window/tab, but there has to be something to identify that other window/tab. It's typically done when the 2nd window is opened from the first. If the two urls are opened independently of each other, I don't know how you can reference one from the other. But, if you are wanting to just refresh the contents, I think the approach I provided above is easier.
  15. Your question is unclear. Are these "pages" both currently open by the same user? I.e. the user clicks a button in one browser window that refreshes the content in another window? Or, is the page with a button something that User A clicks to initiate a refresh in a different page being viewed by User B? Better yet, why don't you explain the problem you are trying to solve that you think that creating such a scenario would solve? It's also important to know if these pages are hosted under the same domain. Do you have control over the content in both pages?
  16. You are using the "keys" from the user submitted data as the field names in your query! DO NOT DO THIS! Never trust the data from the user. Just because you provided the field names in the form does not mean that the user will submit that back. The user could arbitrarily send any field names or even malicious SQL code to expose or corrupt your DB.
  17. You are passing a string as the parameter for "jobTitle" <a href="Careers Results.php?jobTitle=Animator"> Then you are forcing that string to be an integer and comparing it to the original value (a string). A string and the integer value of a string will NEVER be the same. if( (int)$id == $id && (int)$id > 0 ) { Assuming your job titles have an ID (integer) and a Name (string value), you should craft your links to pass the ID as the parameter and not the Name. Use the Name as the text for the link: <a href="Careers Results.php?jobTitleId=5">Animator</a> Then, on your receiving page you can use that value as you intended. Not, you do not need to use those comparisons. Just force the value to an integer and run your query. If the value is 0 or a negative value it will just return an empty result set - which you need to account for anyway: $jobTitleId = isset($_GET['jobTitleId']) ? (int)$_GET['jobTitleId'] : 0; $link = mysqli_connect('localhost','MYUSERNAME','MYPASSWORD','MYDATABASE'); // Connect to Database if (!$link) { die('Could not connect: ' . mysqli_connect_error()); } $sql = "SELECT * FROM careers WHERE jobTitle = {$jobTitleId}"; $result = mysqli_query($link,$sql); $row = mysqli_fetch_array($result); if(!$row) { echo "Record NOT FOUND"; } else { echo $row['jobTitle']; echo $row['jobDescription']; } Also, you really need to look into using prepared statements.
  18. Your RegEx for email addresses is already flawed. Use built-in methods unless, as @gizmola stated, you have a use case that is not supported). As to your second question, if the error message you are referring to is one that is thrown from the DB, then you should absolutely have logic to show the message you define. Never expose DB errors to the user. You should always capture those and show a "friendly" message to the user that does not expose any details they could use to infiltrate the system.
  19. I think what you are after is having the course ID be the VALUE of the option (which is what is sent to the server) and the Course ID as the LABEL for the option. Also, only SELECT the field(s) you want in a query - do not use '*' $resultset = $conn->query("SELECT course_id, course_name FROM tbl_courses"); while($row = $resultset->fetch_assoc()) { echo "<option value='{$row['course_id']}'>{$row['course_name']}</option>"; }
  20. Not "horrible". There are use cases where that makes more sense than labels. E.g. when designing a form for a mobile device where screen real estate comes at a premium.
  21. For that matter, why have $obj2 at all! Just use $obj->Location where you want that value.
  22. Before you do that, you can verify if that is the problem. View the source of the page where the full name is not displayed and see if it is there in the content, but in such a way that it is malformed. You originally stated " . . . he is adding descriptions to the photos via a back end form, if he uses an apostrophe as in O'Sullivan for example, when he saves the entry, the description text does not show at all." First, I think it would be unlikely that output of the descriptions would be within an attribute. It might make sense if using the ALT attribute for an image, but that isn't normally "displayed" on the page. Second, if the problem is something akin to what @Barand states, I would expect "O" (in O'Sullivan) to be displayed as the description. I would suggest first checking the database. Is the full value of the description saved? If yes, then you have a problem with how the output of that value is done. Is the field empty or only containing the value before the apostrophe? If so, then the problem is with saving that content (although you could still have an output problem once you solve that). My guess is that you have a problem in saving the data, but I would expect there to be failures if data with apostrophes were not being handled in the code. For example, if the description was one of the DB fields for images, then a malformed SQL statement would not save an image but not the description. So, I am thinking one of two things: 1) The descriptions are saved to a separate table after the image record is saved. In this instance the SQL to insert the description record could fail after the image record was saved. If errors are suppressed there may be no outward display of a problem. 2) The workflow involves creating the image record first and then adding a description value in that same record as a second use case. In this scenario, the first record would save the image record. But, when attempting to update the image record with a malformed query it would fail. Again, if errors are suppressed, there may be no indicator that there was a problem.
  23. I see no "link" in your code. I assume that the function l() is creating the links. You could find that function and modify it to take an additional (optional) parameter for the class. Then modify the code to insert that optional parameter value as the class. EDIT: Or do what @requinix said.
  24. You previously stated Based on that comment, this might make more sense: while ($stmt -> fetch()) { $users[$role][$id] =[$fn, $ln]; } You will then have a multidimensional array in a logical format based on the data, like this: array ( [Chef] => ( [8] => ('FName', 'LName') ), [Manager] => ( [15] => ('jon', 'smith'), [2] => ('Chelsea', 'Hockley'), ) ) You could then iterate over the results something like this foreach($users as $role => $roleUsers) { //Can add a header for each role here foreach($roleUsers as $userId => $userData) { //Within this loop have the following variables: // - $role // - $userId // - $userData['user_firstname'] // - $userData['user_lastname'] } }
  25. The title of your post was with regard to how much mocks should be utilized in Unit Testing. But, in your post you state you feel there is a lack of Black Box testing. Black Box testing is a form of User Acceptance Testing, not a form of Unit Testing, so the title and the content of your post are contradictory. With regard to Unit Testing, there is no "correct" amount that should or should not be comprised of mocks (in my opinion). It should be dependent upon what it is being tested. Now, if your question is really about whether Unit Testing (with or without mocks) replaces the need for Black Box testing, then the answer is No: Unit Testing and User Acceptance Testing are on opposite ends of the spectrum. Micro vs Macro.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.