-
Posts
5,450 -
Joined
-
Days Won
175
Everything posted by mac_gyver
-
PHP Parse error: syntax error, unexpected '<'
mac_gyver replied to thesunlover's topic in PHP Coding Help
php syntax errors are reported on the line where php encounters something it cannot understand within the current context. the actual problem is usually prior to the line where the syntax error is reported. post lines 1-19 exactly as they are in the file, using this forum's <> menu button. also, since this is a template system of some type, there's no telling what exactly the meaning is of any of the characters we can see in that snippet of code, if the initial/final double-quotes are part of the code or added by the OP, or even if we are seeing all the characters because the code wasn't posted here as code. -
PHP calc price with different time range cost
mac_gyver replied to kit123321's topic in PHP Coding Help
please post the actual code and output in the forum, using the <> menu button. pictures are impossible to use as input for testing. -
PHP calc price with different time range cost
mac_gyver replied to kit123321's topic in PHP Coding Help
first in a question and $time1 = ... $time2 =... values buried in a picture of code in this post - then in a non-picture example in this post - the $time1 and $time2 are the start/end of one rental instance. the date-time ranges the OP listed in those examples are between those $time1 and $time2 values, with a break at midnight, so the resulting ranges are per day, pre rate on each day, for that specific rental period. -
PHP calc price with different time range cost
mac_gyver replied to kit123321's topic in PHP Coding Help
it appears that the OP is asking for any single rental instance to be automatically broken down by amount per day, per rate. his later examples aren't for x different rentals, but for one rental broken down into those date-time parts. -
PHP calc price with different time range cost
mac_gyver replied to kit123321's topic in PHP Coding Help
do you actually care if the breakdown lists the specific time part or would something that looks like the following, which is simpler to code, tell you what you want to know - Array ( [2022-04-08] => Array ( [Norm] => 528 [Peak] => 708 ) [2022-04-09] => Array ( [Peak] => 256 [Norm] => 1568 ) ) -
Need help with displaying information on page using ID from database
mac_gyver replied to cyber15's topic in PHP Coding Help
this is a commonly used method. if your code doesn't work and you cannot determine why, you will need to post all the relevant code needed to preproduce the problem. -
just posting a snippet of your code doesn't help, because it doesn't show how you are using that code. for all we know, you aren't actually calling that function, aren't calling it with any input value, aren't using the return value at all, or could be assigning a value in a comparison, rather than making a comparison. when you have code that doesn't work, and you cannot determine why, you need to post all the relevant code needed to reproduce the problem.
-
you always need error handling for statements that can fail. you should also insure that you have php's error_reporting set to E_ALL and display_errors set to ON, in the php.ini on your development system, so that php will help you by reporting and displaying all the errors it detects. if you run this code on a live/public server, you would instead set display_errors to OFF and set log_errors to ON. the mail() function returns either a true or a false value. for a false value, php will either display or log the actual error information, so that you will have an indication of the call failing. however, in your code for a false value, you should log your own information consisting of the datetime, the php error that occurred, and the parameter values that were supplied to the mail() call. this will let you debug problems that are occurring due to things like email addresses that cause an error. for a true value, because email can be unreliable, you should actually log or insert rows in a database table with the same information, so that you can check if you are receiving all the emails that are being sent. once you do the above you will probably get errors about an invalid mail header, a missing From: header, and/or errors about relaying restrictions. the mail headers must contain a From: email address. the syntax is From: email address \r\n this email address is NOT the address that was entered in your form. these emails are not being sent from the user's email address (except perhaps during testing that you may have done using an email address that does correspond to your web hosting.) they are being sent from the mail server at your web hosting. the email address in the From: header must correspond to your web hosting. you can put the entered email address into a Reply-to: mail header. the are a number of issues with the posted code. the most immediate problems are - the code is not indented properly, so you cannot see what exactly it is or is not doing. the current code will attempt to sent the email, even if the entered email address is not valid. you should actually store the user/validation errors in an array, using the field name as the array index. then, after the end of all the validation logic, if the array is empty, use the submitted data. this will simplify all the nested conditional logic. to display the errors, at the appropriate location in the html document, you would test if the array is not empty, then either loop over or implode the contents of the array to display the error messages. the $body variable is being reassigned on each pass through the foreach(){} loop. this leaves you with only the last checkbox message as part of the body. since there could be any number of checkbox messages, i recommend that you add each one to an array, inside of the loop, then after the end of the loop, implode them with whatever markup you want between them, then append this to the end of the main message body. don't write out code for each possible value. if you had 10 checkboxes, would writing out all that conditional logic 10X make sense? you should use a data-driven design, where you have a data structure (array or database table) that holds the definition of the data. for the checkboxes, you would have an entry in the defining array for each checkbox. the main array index would be the values (1,2,...) each entry in the main array would be an array with elements for the label, and the mail body text. you would use this defining data structure when dynamically building the checkbox markup, when validating the submitted checkbox values, and when adding the text to the mail body.
-
Can this email validation page be improved?
mac_gyver replied to foxclone's topic in PHP Coding Help
that error is due to the above line of code, which is something that you changed in the code. when you got that error message, did you even look at the code to try and find out what's causing the problem? at this point, you are making changes to the code that are introducing errors that didn't exist before and are not even attempting to find and fix your own problems. this error, if you read it and notice where the output is occurring at, happens to be the line where the previous warning about the $email variable is being output. the previous warning being output to the browser is the output that's preventing the header() from working. -
Can this email validation page be improved?
mac_gyver replied to foxclone's topic in PHP Coding Help
wouldn't those Warnings indicate that the variables don't exist at the time they are being echoed? i recommend using php's Null Coalescing Operator to prevent those errors - https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce <?php echo $var ?? ''; // echo the variable if it exists, or an empty string ?> next, one of the points made was to apply htmlentities to external, unknown, dynamic values when used in a html context - <?php echo htmlentities($var ?? '',ENT_QUOTES); ?> lastly, if you look at what the code is doing, especially the part that you know works, i.e. the email specific code, you will see what the variable names actually are. -
Trying to make two buttons redirect to two different pages
mac_gyver replied to Lani-Skyy's topic in PHP Coding Help
there's not really any point in using a post method form to pick which page to go to using a header() redirect (which causes a get request for those pages, the post data won't exist after the redirect anyway.) if you are doing this so that you can have 'buttons' to click on, just use a link that is a button. -
Can this email validation page be improved?
mac_gyver replied to foxclone's topic in PHP Coding Help
this is random nonsense. that line is the syntax you would use if putting the setting into a php.ini file. it's not the syntax for putting the setting into a php file and if it was the correct syntax (which your first post in this thread contains), it would be php code and would go after the opening php tag. the current error you are getting, which you apparently didn't even read to determine that the output that's preventing the header() from working, is occurring on line 1 of your file. that's the random line you added before the opening php tag. if your dynamic pages are being cached in the browser, you need to setup your web server's configuration, so that it tells the browser to never cache .php files. -
Can this email validation page be improved?
mac_gyver replied to foxclone's topic in PHP Coding Help
the original posted code has an unset() statement for the specific session variable, that works as expected for me. -
Can this email validation page be improved?
mac_gyver replied to foxclone's topic in PHP Coding Help
most likely the session_start is failing. do you have php's error related settings set as suggested so that php will help you by either displaying or logging all the errors it detects? when i tested and bypassed the fact that i wasn't actually sending the email, the success message worked as expected and i got the red navigation link back to the home page. -
Can this email validation page be improved?
mac_gyver replied to foxclone's topic in PHP Coding Help
phpmailer would only replace what the mail() call is doing. it has nothing to do with the form or css on the page. -
Can this email validation page be improved?
mac_gyver replied to foxclone's topic in PHP Coding Help
at the success point in the form processing code, you can log or insert the data in a database table so that you have a record of what should have been emailed. some mail servers are configured to silently ignore some invalid attempts and the code could appear like it's sending, when it actually isn't. -
Can this email validation page be improved?
mac_gyver replied to foxclone's topic in PHP Coding Help
if you apply all the corrections and suggestions, you should end up with something that looks like this (tested except for actually sending the email) - <?php // initialization session_start(); $email_contact = "help@foxclone.com"; $email_website = "webmaster@foxclone.com"; // definition of permitted types/subject/category. use to dynamically build the option list, // pre-selecting any existing choice, and used in the validation logic $permitted_types = ['Questions', 'Report Problem', 'Suggestion', 'Other', 'Website Problem']; $post = []; // array to hold a trimmed working copy of the form data $errors = []; // array to hold user/validation errors // post method form processing if($_SERVER['REQUEST_METHOD'] == 'POST') { // trim all the data at once $post = array_map('trim',$_POST); // if any of the fields are arrays, use a recursive call-back function here instead of php's trim function // inputs: name, email, type/subject/category, message - all required // validate the inputs if($post['name'] === '') { $errors['name'] = 'Name is required.'; } if($post['email'] === '') { $errors['email'] = 'Email is required.'; } else { // while it is true that the following email format validation will produce an error // for an empty value, you should specifically tell the visitor what is wrong with what // they submitted if (false === filter_var($post['email'], FILTER_VALIDATE_EMAIL)) { $errors['email'] = 'The Email Address you entered does not appear to be valid.'; } } if($post['type'] === '') { $errors['type'] = 'You must select a Type/Subject/Category.'; } else { // you will only see the following error due to a programming mistake or someone/something submitting their own values if(!in_array($post['type'],$permitted_types)) { $errors['type'] = 'The selected Type is invalid.'; // you would want to log the occurrence of this here... } } if($post['message'] === '') { $errors['message'] = 'Message is required.'; } else { if(strlen($post['message']) < 10) { $errors['message'] = 'The Message must be at least 10 characters.'; } } // if no errors, use the submitted data if(empty($errors)) { // apply htmlentities() to help prevent cross site scripting when viewing the received email in a browser $formcontent = htmlentities("From: {$post['name']}\r\nEmail: {$post['email']}\r\nSubject: {$post['type']}\r\nMessage: {$post['message']}", ENT_QUOTES); if ($post['type'] === "Website Problem") { $recipient=$email_website; } else { $recipient=$email_contact; } // add $post['email'] as a Reply-to: header if desired, it is one, valid email address at this point $mailheader = "From: $recipient\r\n"; if(!mail($recipient, $post['type'], $formcontent, $mailheader)) { // an error // setup the user error message $errors['mail'] = 'The email could not be sent, the site owner has been notified.'; // system error handling goes here... - datatime, get the last error message, include the mail parameter values... // at this point, all parameters are either an internal value, have been validated they they are just an expected value/format, or have had htmlentities() applied. } // if no errors at this point, success if(empty($errors)) { $_SESSION['success_message'] = "Mail Sent. Thank you {$post['name']}, we will contact you shortly.."; die(header("Refresh:0")); } } } // html document starts here... ?> <?php // display any success message if(!empty($_SESSION['success_message'])) { // for demo purposes, just output it as a paragraph. add any markup/styling you want echo '<p>'; echo htmlentities($_SESSION['success_message'], ENT_QUOTES); echo " - <a href='index.php#home' style='color:#ff0099;'> Return Home</a>"; echo '</p>'; unset($_SESSION['success_message']); } ?> <?php // display any errors if(!empty($errors)) { // for demo purposes, just output them as a paragraph. add any markup/styling you want echo '<p>'; echo implode('<br>',$errors); echo '</p>'; } ?> <?php // (re)display the form here..., re-populating the fields with any existing values ?> -
Can this email validation page be improved?
mac_gyver replied to foxclone's topic in PHP Coding Help
it's your contact form. for those users that it may not work for, how could they let you know? -
Can this email validation page be improved?
mac_gyver replied to foxclone's topic in PHP Coding Help
there's something that can be fixed, simplified, and even removed in just about every line of code. the code is insecure (several places), provides a bad User eXperience (vague, cryptic user messages and it appears that the form and from processing code are on different pages), contains unnecessary and unused variables and code, has no error handling that would tell you (the developer) when and why it doesn't work, and contains an operational problem that will probably make it not send emails from actual visitors (which may have actually worked for the testing you did.) a list just going from top to bottom - the php error related settings should be in the php.ini on your system, so that they can be changed in a single place. when you put your application onto a live/public server, you want to log all php errors (you don't want to display them as this gives hackers useful information when they intentionally do things that cause errors.) if the php.ini on your live server is already setup to do this, you don't have to touch your code when moving it. with the settings in your code, you have to find and edit/remove these lines of code every place they exist. Keep It Simple (KISS.) you should detect if a post method form has been submitted, rather than to detect if a specific field is set (and don't try to detect if the submit button is set because there are cases where it won't be.) by hard-coding a specific field in the test, you are creating more work every time you write new code. the two lines after the main comment in the code are configuration settings. any value that is application specific in the body of the code should be set in this section, so that you don't need to go through the code to find all of them or to remove them when posting code in a help forum (do you really want your email addresses to get indexed by search engines on phpfreaks?) despite you editing the first of these two variables, neither are being used anywhere in the code. the died() function is ridiculous and has been floating around on the internet for years. you should display any user/validation errors when you re-display the form and repopulate the form fields with any existing entered/selected/checked values, so that the visitor doesn't need to keep reentering things over and over. the form processing code and the form should be on the same page. the user should not need to be pressing any keys to get to the point of correcting any errors. this function does not support doing any of this. the long list of isset(), which are now empty(trim()) calls, is pointless. firstly, if you had a form with 30 fields, would writing out a statement like this make sense? (your answer should be no.) next, except for unchecked checkbox/radio fields, all other fields will be set once the form has been subtitled. this line does nothing useful. don't copy variables to other variables for nothing. this is just a waste of time typing and making typo mistakes. something that would be useful, would be to trim all the data values, before validating them. this can be done with one single line of code, by keeping the input data as a set, in an array variable, then operating on elements in this array variable throughout the rest of the code. use the same name for any particular item throughout the code. you are referring to one item as 'type', 'subject', and 'category'. you should store user/validation errors in an array, using the field name as the array index, and don't store html markup as part of the message. this will let you preform dependent validation tests only when appropriate, output the error next to the corresponding field if you want, and keep any markup/styling in the html document where it belongs. to test if there are no errors, the array will be empty. to display the errors at the appropriate location(s) in the html document, you would test if the array is not empty. as @gizmola already pointed out, use php's filter_var with the FILTER_VALIDATE_EMAIL flag. the if($subject='') { line only uses one =, so it is an assignment operator, not a comparison operator. the next test, if(($subject)!=('Questions'||...)) { doesn't work at all. you would need an array of the permitted choices (which you should have anyway, so that you can dynamically build the select/option menu), then use in_array() to test if the submitted value is not in the array of permitted choices. the clean_string function is another piece of junk found on the internet. delete it and forget you ever saw it. it doesn't even do an case-insensitive replacement, so just including a capital letter in any of the values will bypass it. you are also not using the $email_message that's being built with calls to it in it. any external, unknown, dynamic value that you output in a html context, such as an email body or on a web page, should have htmlentities() applied to it to help prevent cross site scripting. these emails are NOT being sent from the email address that someone has entered in the form (except perhaps during your testing.) they are being sent from the mail server at your web hosting. the From: mail header must contain an email address that corresponds to your web hosting. you can include the submitted email address as a Reply-to: mail header, after validating that it is exactly and only one validly formatted email address. the error handling for the mail() call should setup and display a helpful message for the visitor, e.g. - The email could not be sent, the site owner has been notified, and you would LOG all the information you have abut the problem such as the datetime, the actual error returned by the mail() call, and the values that were used in the mail() call. by sending the response email to the arbitrarily submitted email address, you are allowing spammers/bots send email through your mail server. forget about doing this. just setup and display the success message. you should actually switch to use either the phpmailer or swiftmailer class. they take care of formatting message bodies and mail headers, so you will have more success at getting your emails to work. after the successful completion of the form processing code (no errors), you should perform a header() redirect to the exact same url of the current page to cause a get request for that page. this will prevent the browser from re-submitting the form data if the user reloads the page or browses away from and back to that page. if you want to display a one-time success message, store it in a session variable, then test, display, and clear that variable at the appropriate location in the html document, not forgetting to apply .htmlentities() to any external, unknown, dynamic value in the message. -
When i press publish button code can't run
mac_gyver replied to Ehsan_collboy's topic in PHP Coding Help
where in your markup are the <form ...> </form> tags for the post method form? -
Contact form does not work on dynamic site (blank data)
mac_gyver replied to rsdias's topic in PHP Coding Help
edit: it turns out the main problem isn't in the form or form processing code - the reason for the incorrect operation of the form(s) is because the markup on the page is broken. there's an opening <form .. tag on line 33 in navbar.php, for a search feature, that is never closed. since nested forms are invalid, any <form tag after that point on the page is ignored. i determined this by noticing the browser address bar changing to include the form field values, meaning a get method form was in effect. since the intended form is a post method form, i searched through the code to find all form tags, leading to the one on line 33 of navbar.php, with no corresponding closing </form> tag. you need to validate all your resulting web pages at validator.w3.org some items for your form processing code - the form processing code and the form should be on the same page. this results in the simplest code and the best User eXperience (UX.) the form processing code should first detect if a post method form has been submitted, trim, then validate all the input data, storing user/validation errors in an array using the field name as the array index, then only use the data if there are no validation errors. if there are validation errors, you would display them when you re-display the form and re-populate the form field values with the existing values so that the user doesn't need to keep reentering data over and over. they can just correct the validation errors. the only redirect in your code should be to the exact same url of the current page to cause a get request for that page. this will prevent the browser from trying to resubmit the form data if the user reloads the page or browses away from and back to that page. if you want to display a one time success message, dialog box, alert,... store the message in a session variable, then test, display, and clear that session variable at the appropriate location in the html document. -
Contact form does not work on dynamic site (blank data)
mac_gyver replied to rsdias's topic in PHP Coding Help
the only thing we can deduce based on the above two items is that there's something wrong somewhere, starting with the form and ending with however the code (finally) reaches the 'home' page. to directly solve this, we need see the actual (not a picture) of all the code needed to reproduce the problem. this indicates that the form processing code isn't first detecting if a post method form was submitted before doing anything at all, since a link would cause a get request for the page. this also indicates that the form processing code doesn't have any/enough server-side validation logic. the email should never get sent if there's no input data. -
the form definition (each field's - id, label, type, name, placeholder text, choices/options, required attribute, validation attributes, ...) needs to be stored in a data structure (database table or array) and to allow for multiple different forms, the data structure should hold multiple definitions, each one receiving a unique id (auto-increment primary index.) the logged in user would then select which form definition to fill in, or if only one definition, be presented with that form. to save each field's entered/selected/checked value, you would need to use ajax to submit the data to the server. the storage of the data on the server would be similar to a database based shopping cart/ordering system, where you would have a table holding the unique/one-time information about the instances of a form being filled out with - an id, the user_id, the form_id (from the defining structure), datetime, status, ... this establishes a form_instance_id. you would use this id to store the submitted form field data in a second table with - an id, form_instance_id, form_field_id, value, ... when the visitor returns to the site and logs in, you would query the data to find if there are any form(s) in progress (the status column would be a value other than the one that corresponds to 'complete'.) you would give the user the choice of picking from among the incomplete form(s) or starting a new instance of a form. if they pick an incomplete form, you would query for the existing data values to re-populate the fields with. when you output the form, you would set the focus to the field after the last submitted value, i.e. the next form_field_id after that in the last row in the table holding the submitted data.
-
Contact form does not work on dynamic site (blank data)
mac_gyver replied to rsdias's topic in PHP Coding Help
slightly off topic, but don't do the following - $_GET['p'] can be anything and cannot be trusted. by submitting a value that uses directory traversal, any .php file anywhere on your server can get required, allowing for example, an administrative action page to be accessed, since the resulting path/file will exist and that code will happily require and execute it for the current visitor. you must validate all inputs before using them. you must test in your code that the $pagina value is only and exactly a permitted, directly accessible page. back to the topic, we cannot help you with what's wrong with your code unless you post all the code need to reproduce the problem. there are multiple different ways to accomplish a task, and without knowing exactly what your code is, no one can simply tell you what to do to make your code work. -
no. it only involves adding one table, a table that defines the checkbox choices, which i specifically mentioned in a reply. in @Barand's reply that shows the table structures, the user_demo table and your form table perform the same purpose (his table only has columns necessary for the demonstration), his user_transport and your vehicle table perform the same purpose and even look the same (after you fix storing an id instead of an abbreviated name), and the transport_type table is the checkbox choices defining table. no, the type of loop is correct, what it is looping over is not. if you look at both the code that he and i have posted, at the point of producing the checkbox markup, you will see that everyone is using a foreach loop, but we are both looping over the definition of the checkbox choices, adding the checked attribute when there is an existing, checked choice. in your code, you are looping over an array of the existing, checked choices. what can that array contain? from zero to three rows of data, resulting in zero to three sets of markup. does that make sense to you? the first three lines of your code make no sense toward getting this task to work. you are testing if some unknown variable is not empty, looping over an array of data, that is apparently the existing checked data, then setting the first variable to be an element of the data you are looping over. actually, that won't work unless there is already at least one checked choice for each one in the vehicle table.