-
Posts
5,954 -
Joined
-
Last visited
-
Days Won
145
Everything posted by gizmola
-
Don't use include. Use require_once(). The fact that you are having these issues speaks to lack of structure in the code you are writing, and the high probability that using MVC with a front controller would be advisable.
-
Please don't ever use w3schools as documentation for anything related to PHP. The PHP manual is complete and well written, and also tends to have some excellent comments illustrating use or warning of gotchas. For example, the manual page says this: So it looks from your recent test that something has already sent the http header prior to trying to set the cookie. That won't work. Irrelevant to your problems, my advice on setting the time, as a more readable and simple solution: $expirationDate = strtotime('+7 days') // <-- 7 days later (make sure your comments are accurate) Where are you running this code during development? Are you by chance using a localhost environment? Since you aren't setting the domain in your setCookie, it is a long standing and well known issue that cookies require a valid domain, and "localhost" is not valid as it has no TLD (.something). At this point, there are 3 recommended choices for a tld configuration you would make on your workstation. (.test, .example or .dev). .test and .example are reserved in the RFC's so there is no issue adding a domain to your workstation in a "/etc/hosts" files mapping it to 127.0.0.1. .dev was purchased by Google, and is unused, so many people have decided to use that for development, and is known to work fine and have no conflicts. I personally use www.something.test for development projects, so I'll map both 'something.test' and 'www.something.test' in my /etc/hosts file.
-
@HawkeNN I want to clarify some things for you. Most code that was written for PHP 7.x will still run fine under php 8. For the most part PHP 8 added new features. There are "Breaking Changes" that were made, listed here: https://www.php.net/manual/en/migration80.incompatible.php but it is unlikely that is the problem with your code from some of the errors I saw listed. For example, the "headers already sent" error is a common one and has been around since php 3 at least. It has to do with code that sends output to the browser (as in the case of a script that intermixes HTML and php) and then tries to set HTTP header values. At that point, the HTTP request has already been sent with whatever headers it had, and it's too late to add or modify them. PHP session use is one function that sets header values because it sets a cookie. Some of the advice that you got is related to common techniques for trying to solve the issue. Equally important is your hosting configuration for PHP. Changes to the configuration of PHP from a version upgrade, can turn on settings that might have been off previously, or warnings being emitted that weren't before. This can then trigger output which also causes the "headers already sent" message. I suspect that this is part of your problem here, and really requires some debugging of your hosting setup. This was already brought up to you, in that there will be a php.ini (and often other assorted xyz.ini files that are included by the main php.ini) where settings can be made or changed to re-configure php. In conclusion, this is a PHP developer forum. From looking at this thread, you aren't likely to have a good outcome here, because you aren't a php developer. My sincere advice is to just find yourself a developer (this forum is chock full of them) you can pay a fee to, in order to resolve your issues and get your site working again. We have established that the code is bad, and that there is likely a few different things going on that are somewhere between the configuration of your server to possible improvements to the code you have. In other words, this is a problem for an experienced developer that requires debugging. I probably shouldn't say this, but my knee jerk reaction is that getting your code to work is not that big of a job, but looking at a thread like this is frustrating to read, because in my experience it is not going anywhere. There isn't any long term value to it for our forum, and you are not going to become an active member of the forum, nor learn PHP development, so there is nothing in it for us, or the community at large.
-
what would be the best way to store images for a dynamic slideshow.
gizmola replied to alexandre's topic in PHP Coding Help
One thing I forgot to add, is that you need to insure that the input to the hash routine has enough things in it to have a high degree of confidence that the computed file name is unique. So an example might be: $fileName = sha1($user_id . $originalFileName . uniqid($mimeType, true)); Another interesting application of sha1, that you might find useful is the sha1_file function. Optionally you could have a column in your asset table that contains this value, indexed. Prior to storing the uploaded file, you can run sha1_file on it, and use this value to check if any other assets have been uploaded with the same hash. This is a great way to prevent people from uploading the same file repeatedly, if that is something you want to prevent. -
what would be the best way to store images for a dynamic slideshow.
gizmola replied to alexandre's topic in PHP Coding Help
The basics of how PHP handles files is that you set in your php.ini a temp directory. Uploaded files go into this temp directory. You then use the function move_uploaded_file to move it to a destination. What you want to do is use some sort of hashing technique to come up with a name for your file. Typically people also do hygiene on the files, checking things like the extension, mime type, and since these are images, there are routines in the libraries you can use to try and read the meta information from the file and determine that it is what it says it is. You don't want people uploading malicious files that look like images, but are actually root kits or something bad. At the point you are confident that it's a valid image file you want to keep, have your routine create a new name for the file. Do not use or trust the name provided by the uploading user. You can save this name in your database table as "original_name" or something similar if you want. Just keep in mind that people can upload files with all sorts of wonky names containing file path characters and spaces, and you don't want to use those for anything. What most people do is concatenate some things together and pass that to a one-way hash routine like md5 or sha1. Your table should also have the mimetype of the file. Then store the file where you actually want it to be. Whether you want something sophisticated or not depends on you. For example, for organizational purposes, you might want to make subdirectories (your code would need to do this of course) for each authenticated user. This is all up to you. Many people choose to keep the files outside the webroot so that people can't navigate to them directly, but again that is up to you as to whether you want to secure the files in some way or not. So to summarize: You need an asset/media/image whatever table You'll want these columns to store mime_type file_path This is the directory path where you will store the file file_name This is the hashed name you will use with move_uploaded_file to store the uploaded file once you are happy that it is legitimate and you want to keep it original_name Up to you if you want to keep this or not description this is common, if the user is prompted for it. user_id If you track the user that uploads it. You can also maintain this via a many-to-many table created_on Timestamp of the upload Don't accept/move files until you have tested that they are legitimate, based on what you want to allow I believe at this point in time the mime_content_type function is a good way to do this for images. Decide in advance what image types you will accept and limit those in the upload form and check in your php script. You can never trust that someone malicious isn't using a tool to bypass the html/javascript checking you might have implemented in the user UI Once you are happy that the file is ok, compute the name you will store, and make any decisions on the path. Use these to do what you want with the file. Some people will store the filename with the validated mimetype, but that is up to you as to how you want to handle it. It does make it somewhat easier for you as sysadmin of your server to look at files in the directories where you are storing them and find a particular file for the purposes of examining it. You probably want to do that if you do decide to store files below the webroot and allow navigation to them directly to be served by the server from a simple img tag. -
What is wrong with this PHP function code? (Contact Form)
gizmola replied to KathyS88's topic in PHP Coding Help
These are the parameters you provided in the script: $mail->Host = 'localhost'; // Set the SMTP server to send through $mail->SMTPAuth = false; // Enable SMTP authentication $mail->Username = 'myemail@here.com'; // SMTP username $mail->Password = 'myPasswordHere'; // SMTP password $mail->SMTPSecure = 'None'; // 'ssl' or 'tls' or Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted $mail->Port = 25; // TCP port to connect to. For Example: 25 - Simple SMTP. 465 - SSL SMTP. 587 - TLS SMTP. Based on information you get from GoDaddy, $mail->Host should be one of their hostnames. You either need a user/password or you don't. This is information you need to get from GoDaddy. Let's assume that the mail relay server for your hosting plan is 'mail3.godaddy.com'. Then you would need to change this line of code in the script: $mail->Host = 'localhost'; To whatever the actual host is. In the example I provided, then that line needs to be changed to be: $mail->Host = 'mail3.godaddy.com'; This is not an actual godaddy host, so don't try and use that. You need to get the correct mail server host name from your hosting information provided to you by godaddy. As for whitelisting, that depends on the email client you use. For example, I used gmail for most things, so a search on "whitelist {your email client}" should provide you some documentation or articles showing you how to do it. For gmail that would be an article like this one: https://www.whitelist.guide/gmail/ -
Requinix pretty much nailed it. Something has changed, and according to you it was a php upgrade. That upgrade might not only be version related, but could be server configuration related. Often with package installs, configuration files get overwritten, and some setting might have been introduced that prevents something from happening that used to happen. So strictly speaking it could be a lot of things, that nobody here has any visibility into. Looking at your code, this depends on a small javascript timer that repeatedly makes calls to the alert_generate.php script. So there are a few things I'd do to debug this on a surface level: Access alert_generate.php directly. See what the result is. Is there an error being generated or do you get a result? Use the chrome developer tools from the view.php page, and open the network tab. See what is happening there. Are there any javascript errors being generated? If network calls are happening as expected, each request can be inspected to see if it is succeeding or an error is occurring. Since you shared the code, it has to be said: I've seen better code from a high school student working on their 1st project This person didn't apparently know how to use require()? They literally copy and pasted the db credentials into each script rather than putting them in a single include file so they could be shared The database design is humorous. The database code could be really old, and was perhaps retrofitted to mysqli_ but still they should have used named parameters I'm not 100% sure that a clever individual couldn't introduce some sort of sql injection, since the alerting code reads values from a database to then formulate a potentially harmful query Using the php end tag ( ?> ) is bad. Small changes to files that intermix presentation and logic like this can break them My advice would be to go through all these php scripts and remove the end tags The PHP Framework interoperability group has published code standards that are widely adopted, so I include a link here just for reference. You can see that here if you are interested: https://www.php-fig.org/psr/psr-12/ See section 2.2. It's qualified, but in your case, all your php scripts should not have php end tags at the end (assuming that is the last thing in any of the scripts.
-
What is wrong with this PHP function code? (Contact Form)
gizmola replied to KathyS88's topic in PHP Coding Help
So according to Mac's link, as I surmised, you can't relay mail directly from your server via it's mta. Port: 25 SMTP Authentication: False or none SSL or Secure Connection: None Server or Host: The relay server you need to use depends on the type of hosting and script you use. This is apparently why your script doesn't work. It is trying to send mail to your local mta via the smtp protocol. There should be instructions on what the relay server is for your email domain. It is not going to be localhost, but rather some domain name they specify. Changing the script to use the right server should allow it to work. While this has nothing to do with your contact script, as far as the other issues with deliverability, one main issue from the report you provided is that DKIM is not being used. There is nothing you can do about that, as DKIM has to be implemented by the email administrator. I don't know if there is any possibility of having it supported by GoDaddy hosting or not, as it is non-trivial. If you want to know more about it, this article does a good job of explaining the basics so you have a frame of reference: https://www.uriports.com/blog/introduction-to-spf-dkim-and-dmarc/ I don't know the purpose of your server or what types of emails you intend to send, but they will not have a high deliverability score, and thus will likely be spam filtered by some email systems. For the purposes of a contact page, that is not a concern, as you can whitelist your address, but if you will be sending regular/automated emails from your domain, you may encounter problems with other people receiving them. Candidly, Godaddy is not a well regarded hosting company, although many people do use it. Hopefully at very least you are not using shared hosting. -
what would be the best way to store images for a dynamic slideshow.
gizmola replied to alexandre's topic in PHP Coding Help
In general, images are best stored either on a filesystem or in a CDN like cloudfront or akamai. It's enticing to store them in a database that you are already using, but it's highly inefficient. Blob storage in databases is expensive considering that you must query the result from the database in order to then return it to the client. What most people do instead is have a table that stores a path to the image, so that you can have the best of both worlds. -
I should probably add that the secret to determining if recursion allows for something elegant, is to determine if you can reduce the problem down to a discrete examination. In the case of my solution, the insight I depend upon is that I only need to check the outer 2 letter of the string in order to determine if it *might* be a palindrome. Another solution using this insight could also be coded using map and reduce. It also needs to be said that the overhead of recursion means that it is almost never employed, although there are some problems involving nested arrays where I see people using it in PHP.
-
There are no doubt a number of different solutions to this. Here is one. So one way to look at it is that in order for a word to be a palindrome, letters offset from each other must be the same. Treating the word as an array, that means you can check word[0] against word[word.length-1] , and if those characters are the same, then it could be a palindrome. If not, it is definitely not a palindrome. Now if you then remove the outer characters (using shift and pop), and check again, this same process is also valid on the remaining inner string. Thus you have an opportunity to use recursion. You can continue this process until the string you are checking has 1 character or less remaining. If you get to the point that the array of characters has no characters remaining then it was a palindrome. Here is an implementation of this idea: function isPalindrome(word) { let palindrome = true word = word.split("") //console.log(word) if (word.length < 2) { return palindrome } palindrome = (word[0] === word[word.length-1]) if (!palindrome) { return palindrome } word.pop() word.shift() return isPalindrome(word.join("")) } const words = ["HelloWorld", "abba", "abcdecba", "a", "oio", "nevermoreromreven"] words.forEach(word => console.log(`"${word}" is a Palindrome: ` + isPalindrome(word)))
-
What is wrong with this PHP function code? (Contact Form)
gizmola replied to KathyS88's topic in PHP Coding Help
The error you are getting is saying no smtp connection could be made to localhost. Does your server have an mta running (sendmail or postfix)? Does your server have any sort of firewall running that might be blocking port 25? Email configuration for a domain and server is a highly complicated endeavor that involves many different moving parts. It also depends a lot on the type of hosting you have. When you state that "it's sending and receiving other emails" I don't know what that means exactly in your case. There are many things this could be, all of which require a fair degree of system administration skills, and an understanding of your hosting. One possible issue is that "localhost" is not being resolved by your server to the loopback address. About the only suggestion I could make, pretty much as a hail mary attempt, would be to change your script to use '127.0.0.1' instead of 'localhost'. Assuming this is a linux based server, you can check the contents of the /etc/hosts file to see if there is a proper entry mapping localhost to that ip. For mail to have any degree of deliverability direct from a domain, requires lot of things to be setup correctly. This site is an excellent aid in testing and diagnosing deliverability: https://www.mail-tester.com/ If GoDaddy is acting as your MTA, then I would expect that your scripts would be delivering mail to a godaddy mail server, and not to localhost at all, so again, email is complicated, and we really don't have enough information to provide more than a couple of educated guesses as to what your issue is. -
I'm sure there are many such libraries but this one has been used by many people: https://github.com/ddeboer/imap This one comes up as the most used in packagist: https://github.com/barbushin/php-imap
-
This looks like homework .... I understand the idea, and it smells like a recursive exercise, which teachers love, and yet are rarely employed due to the huge overhead involved in building a functional stack. 2 things here: You have code that "looks" ok. Obviously you are having some problems with it, but you have no examples or debugging of what doesn't work Do you expect us to set up an environment and run your code and debug it for you? See #1. So in general, yes, I would say that yes, if this is an assignment, this is an exercise that should involve recursion. This code looks very suspect for a few reasons including that repeat is not shown to be initialized anywhere, and it should be local to the running function on the stack: $repeat = $repeat * $data[$i]['number']; Just off a quick browse of your code, you are trying to combine the reading of the array with the processing of a repeat/close_repeat. You want a recursive function that only handles the repeat/close cycle. So what you need in terms of variables is: index of global array temporary array built, which is return when function completes and is returned to be added to the finalized array. Inside your recursive function you can encounter 1 of 3 things: An entry which you add to your temporary array A repeat, where you calls the function recursively having advanced the start/end index an end_repeat where you duplicate the temp index the #repeat times and return it you increment the index internally, so you need to pass this by reference One trap you probably have is trying to control the other process with a for loop. What you actually want is a repeat--until pattern where you will process starting with index=0 until the index = count(array) -1. PHP does not have repeat/until but it does have do..while, so that is what your control should be based on. Hopefully this leads you to a solution, otherwise, again we need specific code, with your debugging and specific problems you are having with select sections of the code.
-
I provided you a solution that should work. Just keep in mind that rules are processed in order. You need this "catchall" to come at the end/after all the other more specific rules or those other rules will never be reached. So you want: www rewrite rule specific pseudo directory rules like your news/ the catchall to *.php Just looking at where you are going with this, having a routing class and using a front controller pattern where you route everything through index.php which acts as a router, is essentially the direction you are taking your site from the look of it. You can make everything simpler and cleaner by either porting to symfony or laravel (which have many benefits in terms of access to all the other features of those frameworks) or just integrate some routing class into what you have. This looks like a possible solution for you: https://phprouter.com/ With that said there are myriad others, but that one appears to be functional, simple and minimal.
-
The courses I mentioned in the other reply cover design and include layouts with flexbox and grid. https://scrimba.com/learn/flexbox https://scrimba.com/learn/cssgrid You want to keep in mind that your goal is to end up proficient with making "responsive layouts" so you should be at some point absorbing some of the ideas involved in how to have a design that adapts to device viewport. Of course you need to get down the basics first and then I think you can add in the elements that really make things responsive. Responsiveness involves a judgement call on your part... what things should shrink or be hidden at smaller sizes. When it's a mobile phone user, do you stack a menu or replace it entirely with a hamburger button? You figure these things out based on your preference. I mentioned Kevin Powell recently. Go through the free Scrimba course they have with him instructing. If you particularly like his style, then you might want to look at his paid courses. Some are free and some are paid either directly or through a Scrimba membership. In my opinion the Scrimba membership gets you the most bang for your buck, but he has a course on flexbox you can enroll in directly: See links to his various course at https://www.kevinpowell.co/courses/ Powell has this "free" course: https://courses.kevinpowell.co/conquering-responsive-layouts It is being done as a 21 day challenge, with new material being released day by day. The course is just being released now, and only has the first few days of content, but it could be a really good place for you to start. I personally like the idea of Scrimba for people learning as it gets you right to where you want to be within the courseware environment. It also has a very active Discord community you should join if you go the Scrimb route. You can also take the scrimba files and download them, fork your solutions etc, and they host all that for you. But of course for your own projects you need a local environment and code editor, and he is likely presenting that material in a local environment using Visual Studio Code and the "Live Server" extension. One nice thing about Visual Studio Code is that you can add the PHP Intelephense plugin and use it for your PHP development as well. Most pro PHP developers are using the PHPStorm commercial editor, but VSCode is the choice of javascript developers at this point, so if you're doing a lot of both, then VSCode + Intelephense is a good alternative. Powell's free responsive course has an early lesson on the environment and that might be helpful to you to see what he's using for his course.
-
Ease of use vs security is a never ending battle. Try to opt for the simplest solution that also works. You can either act as custodian (allows for you to aid a user when they forget/misplace something) provide no custody, thus insuring a compromise of your system doesn't compromise user assets You can't do both. Not knowing enough about this system, I would question the nature of the vouchers themselves. Does your system know the value and when something is redeemed? You might have a customer service feature that would allow someone to make a new voucher to replace a lost one? That mght be an alternative, but would require your system to have the necessary information and controls available to you to determine the status of a voucher, and be able to revoke/replace it.
-
Just a note: please don't use imgur links. That site is a mess, and the forum allows you to attach and insert images into your posts. I editted your question to do that. It's better for everyone to have the content referenced here. As I answered this in the bootstrap thread you made, I'm not going to repeat my comments but they are relevant. These days, layouts are a lot easier to do using flexbox and/or grid. I would also suggest using an html/css/js sandbox for your prototyping/etc. Here's an article with quite a list of different ones. I did already mention scrimba to you, so you can certainly use that as well. https://www.sitepoint.com/code-playgrounds/
-
I'm not 100% sure what you trying to do. I tried to extrapolate that you are looking for "/something" and wanting to rewrite that to "/page.php?slug=something". Options +FollowSymLinks -MultiViews RewriteEngine On ErrorDocument 404 /404.php RewriteCond %{HTTP_HOST} ^domain.com$ RewriteRule ^(.*)$ https://www.domain.com/$1 [R=301,L] RewriteCond %{HTTP_HOST} !php$ RewriteRule "^([A-Za-z]+)" "page.php?slug=$1" [L,QSA] Since you didn't provide examples of what other rules this "broke", this is my best guess. An important addition is that this rule won't run for existing *.php scripts.
-
The PHP process may not be able to write to the /var/log directory. Assuming it's the apache user that php is running as in this case. Connect to the container and check out the perms for /var/log.
-
The first question I would have for you, is do you have a solid "non-expert" understanding of html5 and css? That is what I would highly recommend to get down 1st. This is a good free course to go through, that is all done interactively in the Scrimba environment: https://scrimba.com/learn/introhtmlcss It's taught by Kevin Powell who is one of the better known css teachers I know of, and has an extensive set of video tutorials on youtube. Before you go further down any path, I would recommend you watch this video, which really helps you get an idea of what these different techs provide you from a design/UI standpoint: If you watch enough of this you'll get to the point where he compares some options (vanilla css, vs tailwind vs Material UI (MUI) vs Bootstrap, and declares: "Yeah Don't use Bootstrap. It's 2022 and you know better!" Nonetheless, this is a professional design guy who has worked for various well known companies and is very experienced, so I won't be an absolutist about this, but you should at least go into whatever phase of learning you are entering knowing more about this. I personally use Bootstrap every week for a client I work for, and I would certainly love to be able to move on from it now, but I'm stuck with a giant code base that is tightly integrated with it. At least do your research. Absolutely you should be using the latest version if you do use it. I have found that it is actually pretty easy to use in most cases, however this guy has a complete course on it, and most of his videos are really good: One thing to keep in mind is that Bootstrap does have places where to really take advantage of some of the widgets, you also need to have a working understanding of javascript, in order to integrate it with what you are doing. That is going to be true of many other css frameworks and approaches. It also needs to be said, that whether or not you should be using Bootstrap is a significant question, as there are other css frameworks that have become extremely popular, most notably Tailwind CSS. There are a number of other popular css frameworks, many of which are better suited to customizing the look and feel of things, or have a philosophy that is a bit more modern than what bootstrap has (given that Bootstrap is pretty old at this point, even though it has been updated). Here's an intro to tailwind and a complete course by a guy who has a lot of courses on Udemy, and was actually paid to make a professional level course on Tailwind that is again free on youtube. It is project based, but only one project in this case. If you like Tailwind as an approach then you probably want to look at TailwindUI and/or DaisyUI which build upon Tailwind and are closer to what you would get with much of Bootstrap.
-
There are functions and an entire database class you didn't include that is mysterious. Here's a simplified functional spec Initialize your variables, get initial statistics Get the largest timestamp value in the database. At the end you can use this to update any rows that need to be cancelled because there was no importer entry This assumes that every row has some sort of timestamp row. It appears that way, but you didn't provide the format. Import the file Check that there are entries. You don't want to cancel the entire userbase because the import was flawed Get pre-import statistics for active/cancelled One group by query for this will give you both numbers. SELECT COUNT(*) as count_of, memberStatus FROM Members GROUP BY memberStatus No need to pre-sort import data foreach through the import data SELECT id, status from Member where id = import id If row is found Based on ID, update status, timestamp If it's an actual datetime/timestamp you can do this with column = NOW() This guarantees that a found ID column gets its timestamp updated regardless of the status Based on status add to appropriate bucket rejoined was still status 1 if row not found Add new member Update to new member count When complete, SELECT COUNT(*) FROM Members WHERE "timestamp/updated" column is <= original timestamp you queried during initialization. These are the rows you now need to cancel, so store in your summary array as needed UPDATE Members SET status = 2 WHERE WHERE "timestamp/updated" column is <= original timestamp you queried during initialization At this point you should be able to make your final reporting. Count the arrays for new/ongoing/rejoined. Use the cancelled count# you got from the summary. You probably want to get an initial count of all existing rows via SELECT COUNT(*) but if all rows have a status of 1 or 2, then you can just use the counts from the GROUP BY query summed together.
-
I'm not sure what you want from us, given an outline of your requirements and a basic list of steps. You know what you want to do, and the code doesn't work right or count right, so that means you have bugs. We can't debug your code without seeing it. Here are a few thoughts based on list of steps: This is a terrible idea. There is no reason to update rows of the entire table to inactive, only at some later point to set them back to active. Don't change rows you don't need to change. This is really unclear. What is the format of the "import" array? Are there ID's? I don't see how you could classify anyone as a "Left user". If they were not found, then they should be added as a new user. Thus all users are either found (existing) or not found (new). It seems like there are a number of baked in assumptions here that aren't clear, starting with where this import file comes from. What constitutes "active" state in this system? What exactly is the format of the import file?
-
And everything I wrote previously still applies. let json_array = {} json_array.excludes = [] // Use array method json_array.excludes.push("a") json_array.excludes.push("b") //array syntax json_array["excludes"].push("c") console.log(json_array) I Updated the codepen as well with this example code.
-
Personally, I would recommend uninstalling xamp and using docker. There are a lot of projects out there that offer a docker-compose that orchestrates a lamp environment for you. Devilbox is a massively complete project that offers a myriad of different configurations (not just lamp), but there are many others, not to mention lots of tutorials showing how you can create your own. I even made a project myself to support some of the work I do. I have seen a good deal of discussion of people who primarily make Laravel apps using Laravel Sail, but it can be used for any php project afaik. With that said, if you absolutely must have something similar to what xampp provides, people seem to like Laragon.