Psycho
Moderators-
Posts
12,167 -
Joined
-
Last visited
-
Days Won
132
Psycho last won the day on December 3
Psycho had the most liked content!
About Psycho

Profile Information
-
Gender
Not Telling
-
Location
Canada
Recent Profile Visitors
The recent visitors block is disabled and is not being shown to other users.
Psycho's Achievements
-
I agree 100% with @requinix about setting the type of the field to a numeric input. However, I am a belt and suspenders type of programmer. UI constraints are great for helping the user to avoid common data entry errors, but I believe all such validations should have server-side controls (what if the user POSTed a form outside the UI?). The problem is you are making the problem harder than it needs to be. Why do you only care about '£' character? Just because you are accidentally copy/pasting that character doesn't mean you wouldn't have issues with other characters. So, rather than trying to exclude only that specific, arbitrary character - you should remove all characters that would create an invalid number. Or, conversely, you could detect that the value is not a valid number and return the user back to the input page showing an appropriate error. The choice would be a business decision. Taking the first approach, here is one way to do it: function forceToNumber($value) { //Remove everything that is not a digit or decimal point $value = preg_replace('/[^\d.]/', '', $value); //Check if there is more than one decimal point if(substr_count($value, '.') > 1) { //Remove everything from the 2nd decimal $value = substr($value, 0, strpos($value, '.', strpos($value, '.')+1)); } //Retur4n value as a float return (float) $value; } I'm sure there is a more elegant way to deal with possible multiple decimal points (possibly with a single regex), but I've not worked with Regex for quite a while.
-
Help with an update query using a$_SESSION variable
Psycho replied to mike3075's topic in PHP Coding Help
You should follow @mac_gyver's advice. However, I wanted to weigh in on why your code was failing. When PHP does string interpolation within double quoted strings it will attempt to parse variables. However, when you are dealing with anything but a simple $variable name, you have to take care so they will be interpreted correctly. For example, you can't use and $arrayVariable['foo'] on it's own - you have to leave out the single quotes of the array key OR include it within curly braces, such as: $string = "Name of user = $user[name]}"; $string = "Name of user = {$user['name']}"; However, you are trying to use a variable within a $variable and have it interpreted within a string: $sql1 = "UPDATE cd006ccals SET ccalcourt = $_SESSION['vartestccalcourt' . $i] WHERE ccalid = ".$key; To be honest, I'm not sure if what the format would be to make that work for what you were trying or if it's even possible. I would just create a temp variable and then include that within the full string variable. Again, this is not what you should do with this use case - use prepared statements as noted above. for ($i=0; $i<5; $i++) { $name = $_SESSION['name'.$i]; $string = "The name as position $i is $name"; echo $string; } -
I would agree with @Kicken that limiting users to just a-z characters (which your original Regex wasn't doing, but appears that is what you intended) could be problematic for users with accented characters. Plus, that validation is not considering hyphenated names which is common in last names for married women (e.g. "Smith-Jones")or names with a quote mark (e.g. "O'Reilly"). Personally, I try not to constrain things such as names too tightly because there are many valid names that could include characters that are not intuitive. And telling someone their name is not valid is a bad user experience. Any relatively current back end storage (e.g. MySQL) should be able to handle anything a user provides as long as the table/fields are set up correctly. The only exception, for me, would be if that data is also used for some secondary (usually legacy) process that would choke on such characters.
-
automatically logout deleted user with ajax no refresh
Psycho replied to ssscriptties's topic in PHP Coding Help
I'd like to add my two cents on this as well. Having a process that automatically logs a user out is a nice to have feature. Ensuring that all service calls check the current status and permissions of the user making a request is a must have feature. You specifically asked about "users when they delete the accounts they're logged into", but that should also include other users that may be logged on who are deleted by a different user. The former would be a fairly trivial task, but the latter would require some type of polling or websocket functionality (as gizmola stated) which, in my opinion, adds unnecessary complexity. If you have all your other value add features then, sure, add that ability. But you would still need to add server-side validation for every request anyway. For an edge case scenario where a user is "deleted" while they are logged in I would be OK with some unhandled errors in the UI as long as I was confident their calls were not being accepted/completed. Not saying there shouldn't be error handling - only that it is not as important as blocking the requests. I would suggest the following: Create a single process/function that validates that a user is "Active" (or whatever that means for your application) and returns the permissions they have (assuming there are distinct permission) Every page load should run that common process. If the user is not active or does not have the requisite permissions for the page being loaded, redirect them to an appropriate error page I assume you have various AJAX driven features. All back-end AJAX calls should call the same common process and if the user is not active or does not have the requisite permissions for the process being called, have the AJAX response return an appropriate error. The client-side implementation will need to check for such errors and react accordingly (I'd redirect to the same error pages as noted above). -
Trying to use GLOB function to create gallery.
Psycho replied to BluApple's topic in PHP Coding Help
First, your two includes at the top and bottom of the page are not within correct PHP tags. Need a ? before the starting PHP. The DIV in your code is in the HTML source, but there is nothing within it. That would seem to indicate that there was no content in the $images array. I'm guessing that the path you provided to the glob function is not correct. Where is the 'photography' folder in relation to where the php file is being executed? -
In a past life, have experience turning dynamic, user generated content via a web page into print-ready PDFs for commercial printing. In that case, the user input on the web forms was converted into PostScript code that was then run through a processing engine (my expertise was in the postscript programming). So, when I had a need to generate PDFs as a PHP hobbyist, I looked for a solution where I could "program" the creation of the PDF in the same way as I did with PostScript. I ended up using the FPDF Library. If you have fairly rigid constraints on the layout of the content, this could be an option. Instead of generating an HTML page and running that through something to convert it to a PDF, this library allows you to create a PFD file in much the same way you would create a web page. I.e. determine "where" on the page you want to put an element, define things like color, font, and then place the elements on the page. However, there is another, simpler option. Instead of emailing the user a PDF, just send the user a link. That link would be to a web page of their quote and then the user can print the web page quote to PDF, the printer, or however they want. I think most shopping sites I use have this approach if I want to print the invoice. This much simpler and less moving parts, IMO.
-
Database connection incl. insert, get update, and delete data.
Psycho replied to LeonLatex's topic in PHP Coding Help
I see what you are trying to do, and I can see why someone might want to do that, but in my opinion that is not a good idea for many reasons. Here are just a few: Any application with a database should have some queries that rely upon JOINs. The above logic could not support JOINs without becoming overly complicated/burdensome. The fact that the code does not seem to rely on any JOINs would seem to indicate the DB structure and usage is not ideal. The code relies upon too many assumptions which may not be appropriate for every table - then you are back to writing queries for those one off situations and are then left with a mix of different processes for interacting with the data Using those functions means you are now interacting with the data in a non-standard way which can create problems for maintainability and readability. A much better approach would be to create classes/objects to interact with the data. It will be more verbose, but the code for each "type" of data (not necessarily data in a single table) can be segregated into separate files for easy maintainability. Then, in your code, you just create an object and interact with the data that way. -
My opinion is that it is not worth whatever benefit you think it will be to use spaces or other extraneous characters as an array key. As Barand was suggesting, you have to be more careful. Otherwise, you create bugs that can be frustrating to find and it can limit you in the future. I recall once where I had a database field with a space in it. I had a function that would query results and return it as an array. No problem, I could reference that value using $dbArray['Field Name']. But then I was rewriting the code as part of refactoring project and instead of a function that returned an array, I instead created a Class and an Object. Now there's a problem. For objects, you normally reference the properties (values) in the format $dbObject->fieldName . That won't work if the property name has a space in it ($dbObject->field Name) as the PHP parsing engine will think the property name ends at the space. You can have property names with a space, but you have to reference them differently. E.g. $object->{'property Name'}. But that format isn't widely used (in my experience) and just makes the code more complicated. It was a big headache to address.
-
How to ECHO which item was found/matched after running "foreach"
Psycho replied to myphp's topic in PHP Coding Help
To be honest, I vacillated between several options. Pretty sure all of these would have worked. if (!empty($foundKeywords)) { if ($foundKeywords) { if (count($foundKeywords)) { if (sizeof($foundKeywords)) { Also considere4d having the function returning a Boolean FALSE if no keywords were found instead of an empty array. But decided that an empty array was simpler. -
How to ECHO which item was found/matched after running "foreach"
Psycho replied to myphp's topic in PHP Coding Help
If you are wanting to know which keyword(s) is/are found, there is one flaw in your logic - it exits the function on the first keyword found. What if there are two or more keywords that are found? Instead of returning true on the first keyword found, I'd suggest adding the found keywords to an array. Then return the array. Also, I would assume you would want to do a case insensitive search. E.g. if you have "spamword1", you would want a match on something like "SpAmWoRd1". If so, you would want to use stripos() Give a look at this: $uri = $_SERVER['REQUEST_URI']; $spam_keywords = [ 'spamword1', 'spamword2', 'spamword3' // WILL BE A LOT MORE HERE ]; function checkKeywords($uri, $keywords) { $foundKeywords = array(); //Create array to hold found keywords foreach ($keywords as $keyword) { //Iterate over list of keywords if (stripos($uri, $keyword) !== false) { //Check if keyword is in $uri $foundKeywords[] = $keyword; //Add found keyword to array } } //Return found keywords return $foundKeywords; } //Check for keywords $foundKeywords = checkKeywords($uri, $spam_keywords); //Check if results are not empty if (!empty($foundKeywords)) { //Keywords were found - display them echo "<p>The following Keywords were found:" . implode(', ', $foundKeywords) . "</p>"; } else { //No keywords found echo "keywords not found"; } -
I'm not well versed in using cURL, but based on what you provided previously your call to the URL you are using is returning the response: 301 error "Permanently Moved" But, you expect to be getting the JSON encoded output for the $allowed_domains array you are creating. I would assume you have tested the url in a browser and verified you are seeing the JSON content? If not, start there. If the content is correct when access via a browser then my best guess is that the web server maybe has some logic to detect programmatic access to pages and is blocking it. I'm pretty sure I've seen something like that before. But your issue has noting to do with the error you first reported. You need to figure out why your cURL request is not retrieving the JSON content you think it should be returning. Although, this is a good opportunity to add additional error handling to your code to cover a scenario where the cURL request doesn't fail, but does not return contents you expect.
-
I assume you got more than that from the var_dump. But, in any case, that response is not an array - correct? That would be why the in_array() function is failing with that error. So now you need to debug why passing your domain (which is not the same in your code above) is causing this error.
-
What you have defined for $domains_content in your first bit of posted code is irrelevant to your error, because 1) it is defined outside your function and 2) you redefine that variable shortly before the error // URL of the external PHP file $url = 'https://www.domain/domains.php'; // Replace with the actual URL // Fetch the domains $domains_content = fetchDomains($url); So, what is the result of that call? It's apparently not an array. try adding this right after the last line above to see what is actually returned: var_dump($domains_content); EDIT: Correction, the error is in a block of code outside your function, so #1 in my response is not valid
-
I would also add, indicate where the php file that is being executed resides in that directory structure. If you are trying to reference a file with a relative path (vs. an explicit path) knowing the location of the execution file and the file to be accessed is important.
-
@Barand completely agree with your response. But, unless I am missing something, I think there is a step missing in your example code. Shouldn't there be a step to fetch the results? I think $result_list would be a PDO object and not an array of the results. And there is a missing opening curly brace for the foreach() statement - although I consider that a minor typo that I would expect the OP to identify/fix. $sql_list = "SELECT ID FROM dados_socios WHERE usuario = ? ORDER BY ID"; $result_query = $conn->prepare($sql_list); $result_query->execute([$usario]); $result_ary = $result_query->fetchAll(); echo "<select>"; foreach {$result_ary as $row) { echo "<option>ID: {$row['ID']}</option>"; } echo "</select>";
