Jump to content

kicken

Gurus
  • Posts

    4,704
  • Joined

  • Last visited

  • Days Won

    179

Everything posted by kicken

  1. If your goal is to strip potentially harmful comments / metadata from an image, the way to do that would be to use an image library to re-generate the image file without that data. The image magick extension has a function for this. I'm not sure if loading then re-saving an image with GD will accomplish this or not. Trying to just arbitrarily manipulate an image file is a poor approach. Even if it works with your test images, it may not work with all images. You'd need to have a good understanding of the file format so you can parse it and manipulate it properly, which is a lot of work when you can just use an existing library instead. You don't have to use generators and yield to save memory, just reading the file a bit at a time. A simple loop like this: $fp = fopen('file', 'rb'); while (!feof($fp)){ $line = fgets($fp); //do stuff } fclose($fp); will also only use enough memory to hold a line's worth of file data at a time without the complication of a generator. Often, parsing a binary format file is not something you'd do line-by-line anyway. You'd read various chunks based on the file format, possibly seeking to a particular position in the file first.
  2. You can. It'll make a HTTP request, just like a browser would and give you the response data.
  3. Given you've been told that I fail to see how that's a problem. This isn't a "fix my code for me" service, it's a help forum. You're expected to have some basic critical thinking skills and put in some effort of understanding. You should be able to deduce that one persons $conn is another persons $pdo, just change the names as appropriate. Same with any other variables. Everyone has their own conventions and preferences as to what to name thing. So why are you still complaining / whinging about variables if this works? You're just dragging this whole thing out and causing even more confusion about what problems you may or may not have.
  4. So what, just going to ignore my posts telling you what you're doing is not necessary. Ok then.
  5. The old mysql code did not require working with the connection beyond establishing it. PHP would implicitly use the previously established connection. Such implicit things are generally considered poor programming because it can complicate more advanced usages (such as multiple connections). As such, the newer API's do not use the practice, and require you to explicitly use a specific connection in some way or another. With PDO that means you need to use the PDO object created when connecting. Making the variable static within ConnectDB doesn't some how open it up to the world, it only means the value persists across different calls to ConnectDB which lets you avoid having to establish a new connection every time you call the function. You still have to return that connection, and capture it at the point when you call ConnectDB. This is a easy find and replace job. Find: ConnectDB(); Replace with: $pdo = ConnectDB();. You'll have to update ever where you're doing queries anyway, so you can do this too at the same time. By using the singleton trick, you do not have to update every calling location of your function, just your calls to ConnectDB.
  6. You are not capturing the return value from the ConnectDB function, and thus never defining $pdo. function LogMeX2($name , $pwd1) { connectDB(); $Name = md5($name); $Pwd1 = md5($pwd1); $ret = 0; $qValid = $pdo->query("SELECT COUNT(*) FROM LIBusersX WHERE UserKey = '$Pwd1' AND UserN = '$Name'"); $total = $qValid ->fetchcolumn(); // Should only be 1 or 0. if($total == 1) { $qUser = $pdo->query("SELECT User FROM LIBusersX WHERE UserKey = '$Pwd1' AND UserN = '$Name'"); $rs = $qUser->fetch(); $ret = $rs['User']; // Should return 0 or id of the user. } return $ret; } Notice how you are using $pdo for your queries, but prior to that you never actually define it anywhere? You can't say "I defined it in ConnectDB!" because that's a whole different function and variables do not get carried between functions. ConnectDB returns your PDO instance, but you still need to assign that return value to a variable when you call it. $pdo = ConnectDB();
  7. You would need it if you wanted to insert a string like that into your query. As mentioned above though, you're not supposed to be doing that. You're supposed to be using prepared queries which let you keep the data and your query separated. If you just insert the data directly into your query, you open yourself up to potential SQL Injection attacks. The steps for how to convert your queries to prepared queries were outlined above.
  8. If you're only interested in the row count, you should select that. $qValid = $pdo->query("SELECT COUNT(*) FROM LIBusersX WHERE UserKey = '$Pwd1' AND UserN = '$Name'"); $total = $qValid->fetchColumn(); If you wanted both a row count and the data, you could either issue a separate count query or count the rows as you fetch them. $qValid = $pdo->query("SELECT current FROM LIBusersX WHERE UserKey = '$Pwd1' AND UserN = '$Name'"); $total = 0; foreach ($qValid as $row){ $total++; //Do stuff } You use fetch() with the fetch mode set to PDO::FETCH_NUM or PDO::FETCH_ASSOC depending on if you want a numbered or associative array. $qUser = $pdo->query("SELECT User FROM LIBusersX WHERE UserKey = '$Pwd1' AND UserN = '$Name'"); $rs = $qUser->fetch(PDO::FETCH_ASSOC); echo $rs['User']; If you always want to fetch an associative array, you'd specify that as your default fetch mode when you establish your connection with the attribute PDO::ATTR_DEFAULT_FETCH_MODE, then you don't have to specify it in each individual fetch.
  9. Your code in this post used both $conn and $pdo, which is where the confusion began I think. That's irrelevant now though, so lets drop that discussion. You can use whatever variable name you want, so long as you are consistent about it. You do want to change your code to avoid connecting for each query, for at least two reasons. Creating a bunch of connections can exhaust the available connections on your server, meaning some connections may stop working. The most expensive part of talking to a DB is setting up the connection. Having to do that for every query will slow things down Now, changing every function call to accept a parameter is not the only way to accomplish this shared connection. Another way is to use a singleton pattern. This is similar to a global variable but not quite as bad. Generally this is talked about in the context of classes but you can do it with a simple function as well. Your connectDB would look like this: function connectDB() { static $conn = null; if ($conn === null){ $host = HOSTNAME1; $user = USERNAME1; $pass = PASSWORD1; $MyDB = DATABASE1; $conn = new PDO("mysql:host=$host; dbname=$MyDB; charset=UTF8", $user, $pass, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ ]); } return $conn; } static makes the variable persist across different function calls. The first time this function is called, $conn will be null, the if will run, and your connection will get established. On subsequent calls, $conn will hold the PDO object previously created so the if will get bypassed and the existing connection will get returned.
  10. I think you need to create your own error object, ie: $error = new WP_Error();
  11. You can use sprintf to easily ensure the 0 is there for your link. $prev = sprintf('w%02d', $num_week - 1); $next = sprintf('w%02d', $num_week + 1);
  12. Array.map runs through the array passing each element to a callback function and returning a new array. The new array is composed of the value returned from that function. In the callback function here, i will be each task element. The callback returns the requester name of the task. The final a result is an array list of each requester name found in the tasks array. Array.filter also runs the every element of the array through a function and returns a new array. The callback is supposed to return true or false, and if it returns true, the original element is added to the new array. Any elements where the return value is false end up removed from the final array. The callback here takes an element from the arrayA.requsters list and checks if it exists in the requsterList build from the tasks. If it does, the function returns false and that item is stripped from the final array. End result is an array of requesters not found in the tasks.
  13. So, I just realized this was the JavaScript forum not the PHP forum. const arrayA = { 'filters': { 'requester': true } , 'requesters': [ 'GHS Research', 'gw1500se', 'Kicken' ] }; const arrayB = { 'tasks': [ {'project': {'requester_name': 'GHS Research'}}, {'project': {'requester_name': 'Example'}}, {'project': {'requester_name': 'gw1500se'}}, ] }; const requesterList = arrayB.tasks.map((i) => i.project.requester_name); const missing = arrayA.requesters.filter((i) => !requesterList.includes(i)); console.log(missing, missing.length);
  14. Something like this then: $arrayA = [ 'filters' => [ 'requester' => true ] , 'requesters' => [ 'GHS Research', 'gw1500se', 'Kicken' ] ]; $arrayB = [ 'tasks' => [ ['project'=>['requester_name'=>'GHS Research']], ['project'=>['requester_name'=>'Example']], ['project'=>['requester_name'=>'gw1500se']] ] ]; $requesterList = array_column(array_column($arrayB['tasks'], 'project'), 'requester_name'); $count = count(array_diff($arrayA['requesters'], $requesterList)); var_dump($count);
  15. Your array A is still somewhat unclear. Is it like this? $arrayA = [ 'filters' => [ 'requester' => true ] , 'requesters' => [ 'GHS Research' ] ]; And you want to get a count of the values in $arrayA['requesters'] that do not exist in any of the $task['project']['requester_name'] values in array B?
  16. This is probably the true solution. If you want to expand more on the actual problem of getting data dynamically loaded and what you've tried, perhaps we can help you with that and get you a real solution. Your issue with your hack is that you have an iframe boundary that's complicating things. Why is your modal part of the iframe and not part of the main page? Why is your main page controlling the refresh instead of the iframe itself? Removing this boundary will simplify things considerable so I'd suggest if you don't want to re-attempt an ajax solution, you work on removing this boundary problem. Either make the iframe refresh itself (an thus, able to stop itself), or move the modal into the main page so it's not affected by the refresh.
  17. Given you're trying to compare with LIKE, I'm guessing that means the each row has a list of zipcodes in that column, not a single zipcode? Given the column name is dynamic, I'm guessing you have different columns for each state too (ie, FLZips, GAZips, etc). If that's the case, then that is not the proper way to design your database. A column should only contain a single value (ie, a single zipcode) per row, and you shouldn't have multiple columns for essentially the same info. You should have a second table that associates the zipcodes and the state with a business, with a single row per zipcode and state combo. For example: create table business_zipcodes ( businessId int not null, Zipcode varchar(10) not null, State varchar(2) not null ); You'd then join to that table in your select to search for a particular zip code. SELECT * FROM DATA INNER JOIN business_zipcodes on business_zipcodes.businessId=DATA.id WHERE DATA.id=? and business_zipcodes.State='FL' and business_zipcodes.zipcode=? Notice I replaced your variables with ? also. Sticking variables into your query is also another thing you should not be doing (read up on SQL Injection attacks), you should be using a prepared statement with bound parameters. Your code would end up looking more like this: $stmt = mysqli_prepare($con, " SELECT * FROM DATA INNER JOIN business_zipcodes on business_zipcodes.businessId=DATA.id WHERE DATA.id=? and business_zipcodes.State='FL' and business_zipcodes.Zipcode=? "); mysqli_stmt_bind_param($stmt, 'is', $_GET['id'], $_GET['Business_Zip']); mysqli_stmt_execute($stmt); while ($row = mysqli_stmt_fetch($stmt)){ echo '<br><img src="images/Florida.png" style="padding-bottom:8px;">'; }
  18. Is $Florida_Zips supposed to be a column name, or something like a comma-separated list of zip codes? Where does the data for it come from? Your code says the query string, but your example URL doesn't mention it.
  19. Those are two probably unrelated messages. The json error is from JavaScript, telling you it was unable to parse some json data. There is probably either a syntax error in the data, or if the data is coming from an ajax call it might be unexpectedly getting HTML instead. The php.ini warning is your CMS asking you to make that setting change. Presumably there is a reason it wants that done so you should probably do it. If you don't know where to make the change, create a phpinfo() page and it will tell you where the php.ini file is so you can edit it.
  20. Nor could any client just call your function, so why bother with your private hack in the first place? Private vs public functions has nothing to do with the client/browser, but with other parts of your code. A private function can only be called by some other function within the same class, not by code outside that class. Public function can be called by any part of your code. It may seem pointless when your just developing some small-time blog made out of one page and a couple includes but when you get into real programming work it becomes important. I feel like you are either trolling or just feel like your smarter than everyone else. Seems obvious at least that you have no interest in actually learning programming techniques. By all means, keep that hot garbage you call code for yourself, nobody wants it.
  21. Maybe because whatever you're doing doesn't need OOP. Maybe you just don't understand OOP well enough to see the usefulness. It's hard to say. The example class you posted here seems pretty pointless. If you want to see your class fixed up though, <?php declare (strict_types=1); namespace SpyderEyes; class Reflection { protected string $mirror; public function __construct(string $shine){ $this->mirror = $shine; } public function shine() : string{ return $this->mirror; } public function dust() : string{ return bin2hex(base64_encode($this->mirror)); } } try { $reflector = new Reflection(['Mirror, Mirror on the Wall']); echo '<p>' . $reflector->shine() . '</p>' . PHP_EOL; echo '<p>' . $reflector->dust() . '</p>' . PHP_EOL; } catch (\TypeError $error){ echo 'Oops'; } The constructor will throw a type error if you pass a non-string value which you can catch and handle if you want. Since the constructor can only accept a string, you ensure that the mirror property will always be a string and thus do not have to do any checking in the individual methods. One way to dive into the deep end and see how OOP can be beneficial is by looking at the various frameworks that exist. I like Symfony personally and think spending some time using and learning about it can be quite beneficial in showing how useful an OOP approach can be. A couple other reasons why classes are nice: Class autoloading saves you from getting into an include/require nightmare. IDE's can easily parse the classes and provide auto-completion. Yes, return is valid in a function. Returning a value from a constructor is not though. Take your original code that returned false class Reflection { protected string $mirror; public function __construct($shine){ if (!is_string($shine)){ return false; } $this->mirror = $shine; } } What do you expect return false to do there? If you think it's something you can test for to see if the constructor failed, you're mistaken $o = new Reflection([]); if ($o === false){ echo 'Oops'; } else { echo 'Success!'; } That if statement will never be true, $o will always be an instance of Reflection. The return only causes the constructor to stop running, which means your mirror property never gets initialized and thus causes you future issues. This I don't understand at all. Trying to emulate private functions by checking if some session variable exists make zero sense and doesn't actually make the function private at all since all one would have to do to use it is set that variable.
  22. If you don't want PHP to complain about type errors, then stop using strict_types and type hinting. The whole point of those features is to enforce a specific type, so if you're not passing the correct type it's not a "minor error" it's a real error. You cannot return a value from a constructor. The correct thing to do if the data in a constructor is invalid is to throw an exception. This all becomes unnecessary if you ensure the constructor either has valid data, or fails with an exception.
  23. console.log is just for debugging, it shows the value in the browser's developer console, similar to doing a var_dump in php to see a variable on the page.
  24. Because you're only looking at and considering what the browser is doing. As I said, the redirect will work fine, just like it did when I was doing my demo to that company. The problem is that without the exit, any other code in the page after the header will still run. How much of a problem that is, depends on what that page does. In the case of the demo, that code deletes data which is very bad. If you want to try get a better understanding is to use something like curl to request your URL rather than the browser. A browser that sees a Location: header ignores any other output and just requests the new URL. Using curl, you can see the rest of the output. So request your page using curl with and without the exit and you'll see the difference. curl -ik https://example.com/yourpage.php
  25. The redirect happens because the header gets sent, but that doesn't happen until the script is finished. The point of the exit is to force the script to end. As this whole thread has been about, "they can't see the page" is not a valid defense, they can still access it directly by url. I did a code review for a company once that had the exact problem I described in their CMS. I demoed the problem to them by creating a test page in the admin area then logging out. Without logging in again I typed in the URL to their delete page with the ID of the page I created. I got redirected to the login page, everything seemed fine but. After logging in though, one could see that the page had in fact been deleted.
×
×
  • 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.