Jump to content

Psycho

Moderators
  • Posts

    12,159
  • Joined

  • Last visited

  • Days Won

    130

Everything posted by Psycho

  1. 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.
  2. 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"; }
  3. 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.
  4. 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.
  5. 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
  6. 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.
  7. @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>";
  8. Looks like @gizmola missed a right square bracket on the second $_GET value. Try: if (!isset($_GET['t']) || !is_int($_GET['t']) || $_GET['t'] < 0) { header('Location: http://www.baltimorebeach.com'); }
  9. As @mac_gyver stated, the problem is that line to check if the 't' value was sent. The way it is constructed, that condition will return true if the value is not set OR if the value is interpreted as false (which a zero value will be). You state that this was working for over 12 years and no changes were made to the code. I find that unlikely as PHP would have always interpreted a 0 as false in that condition (as far as I am aware). Perhaps that condition was previously written in a more explicit manner to account for a team ID of zero. E.g. if(!isset($_GET['t']) || ($_GET['t']===false) And someone looked at it and thought the code was more complicated than it needed to be and "fixed" it to be simpler. So, your issue turned out to be exactly what I had hypothesized. You can either find all instances where teamID may be used in your code to ensure that a zero value will always work (poor fix) or (the right solution) change the primary key for that team to another value and then change the foreign key references to that ID.
  10. Well, obviously, something has changed. We have no access to the code, the web server, etc. I have provided a "best guess" based on the only piece of information provided: team id is 0. I still think the most likely cause is something due to the value being the value zero. As to not seeing any errors, what level of error reporting do you have enabled. In a production environment, most errors should be suppressed. Have you even inspected the page viewTeam.php (and any included pages) to look at the code? Have you added any debugging logic to see where in the execution the logic is failing to do what you expect?
  11. Without any code, there is no way to make any type of qualified assessment on what the problem is. But, I will venture a guess. PHP is a "loosely" typed language. That means that variables can be used as different types. For example, you can use a string variable "2" as an integer 2. My guess is that there is some condition in the code that tests to see if the team ID is valid (i.e. not false). But, because the integer zero is also interpreted as the Boolean False the test is failing. Here is some mock code of what I am talking about: if(isset($_GET['t'])) { $teamId = $_GET['t'] } else { $teamId = false; } if($teamId == false) { //Team ID is false, don't show the content } else { //Show the team content } A team ID of zero will result in the error condition. You could correct THAT scenario by using the identical condition of !==. But, there can be multiple scenarios where a zero is being misinterpreted and you would have to look at each one to determine what the correct solution would be. There is a reason that most (all) databases start at 1 as the initial primary ID. Assuming this is a primary key in the DB, I would suggest changing that team's ID to a new unique number and updating all associated data.
  12. As @dodgeitorelse3 asks, please show your form code. It is impossible for a single variable (e.g. $_POST['vote']) to have multiple values. I am assuming you have nine checkboxes all with the same name, but different values. That won't work. You need to either create them with different names OR create them as an array. Also, checkboxes are unique in that if they are not checked they are not included in the POST data, so you would want to check that they are set and not just check for the values. If you name each checkbox differently (the value would be unnecessary in this context) <input type="checkbox" name="Juste" value="1"> Juste <input type="checkbox" name="Chavez-Gris" value="1"> Chavez-Gris Then your processing code might look like this if (isset($_POST['Juste'])) { $result = mysqli_query($db,"UPDATE NewBoard SET votes=votes+'1' WHERE lname = 'Juste'")or die ("Fatal Query Error: " . mysqli_error($db)); } if (isset($_POST['Chavez-Gris'])) { $result = mysqli_query($db,"UPDATE NewBoard SET votes=votes+'1' WHERE lname = 'Chavez-Gris'")or die ("Fatal Query Error: " . mysqli_error($db)); } Or you could create your checkboxes as an array (this would be my approach) <input type="checkbox" name="votes[]" value="Juste"> Juste <input type="checkbox" name="votes[]" value="Chavez-Gris"> Chavez-Gris In which case the processing code might look like this //Set variable based on POST value or empty array if none selected $votesArray = isset($_POST['votes']) ? $_POST['votes'] : array(); //Check for each value in the $votesArray if (in_array('Juste', $votesArray)) { $result = mysqli_query($db,"UPDATE NewBoard SET votes=votes+'1' WHERE lname = 'Juste'")or die ("Fatal Query Error: " . mysqli_error($db)); } if (in_array('Chavez-Gris', $votesArray)) { $result = mysqli_query($db,"UPDATE NewBoard SET votes=votes+'1' WHERE lname = 'Chavez-Gris'")or die ("Fatal Query Error: " . mysqli_error($db)); }
  13. I'm looking for a way to perform multiple LIKE conditions on a field without a string of ORs. In a perfect world, MySQL would support something such as WHERE field LIKE (SELECT matchField FROM table WHERE . . . ) Here is my situation: My records in a table we'll call "data" all have a value called an AreaPath which is essentially a hierarchical list. This value is coming from the source data and I have no control over it. Many items will have the same area path. Here is a mock example of what the data might look like: Cars\Autos\Peugeot Cars\Autos\Peugeot\ Peugeot 404\ Cars\Autos\Peugeot\ Peugeot 404\Coupe\1952 Cars\Autos\Peugeot\ Peugeot 405\ Cars\Autos\Toyota Food\Bread\Croissant Food\Pasta\Spaghetti During an import of the data, I'll be creating/updating a table called "areas" with all the unique area paths. areaId | areaPath 1 Cars\Autos\Peugeot 2 Cars\Autos\Peugeot\Peugeot 404\ 3 Cars\Autos\Peugeot\Peugeot 404\Coupe\1952 4 Cars\Autos\Peugeot\Peugeot 405\ 5 Cars\Autos\Toyota 6 Food\Bread\Croissant 7 Food\Pasta\Spaghetti In my database, I have a table called "Groups" where a user can define a group by name: groupId | groupName 9 French Then, the user will be able to define area paths that will be associated with the group (table groupareas). But, the user does not have to define all the distinct area paths only the top levels. For example, if the user selects the area path "Cars\Autos\Peugeot", then it would encompass that specific area path and ALL paths below it (e.g. "Cars\Autos\Peugeot\Peugeot 404\", "Cars\Autos\Peugeot\Peugeot 505\", "Cars\Autos\Peugeot\Peugeot 404\Coupe", etc.) groupAreaId | groupId | areaId 1 9 2 2 9 6 The above example would define the group "French" to include the area paths of "Cars\Autos\Peugeot" and "Food\Bread\Croissant". So, what I need to do is be able to dynamically query all the records that would belong to a particular group based on that data. Like I said above, in a perfect world I could do something like this SELECT * FROM data WHERE areapath LIKE ( SELECT CONCAT(areaPath, '%') FROM areas JOIN groupareas ON areas.areaId = groupareas.areasId AND groupareas.groupId = ? } But, that won't work. So, my fallback solution would be to run two queries. First query the area paths associated with a group and then programmatically build a query with OR conditions. SELECT CONCAT(areaPath, '%') FROM areas JOIN groupareas ON areas.areaId = groupareas.areasId AND groupareas.groupId = ? Then iterate through the results to build this. Note: I would have to also convert the backslashes. SELECT * FROM data WHERE ( areapath LIKE "Cars\\Autos\\Peugeot%" OR areapath LIKE "Food\\Bread\\Croissant%" ) While that would work, I will be running lots of different queries against the data to run various reports on different groups. Having to programmatically create the queries will be inefficient. I'm looking to see if there is a way to pull all the records for any "group" in one query by just changing the groupID. I hope this all makes sense.
  14. I am in agreement with @Phi11W above. There are scenarios where some things need to be processed on a schedule, but that is not always the case. So, it would be helpful to know what you are wanting to "happen" every night and what will "happen" after the one minute when the user clicks a button. Depending on what you are trying to do the best solution can be different. But one of the preferred way to initiate things on a schedule is with a CRON job which is a scheduled task within a Linux server (which is where most PHP implementations are hosted). If you are hosting your application with a provider they likely have a custom interface for setting these up. You would start by creating a PHP file that will run a process (your nightly process or the process to run after one minute of the button click). For the nightly process you you set up the CRON job to run at a specific time each night. You should set up a notification to be sent and report if the process passed or failed. As for the process to run 1 minute after a button click someone may know a better process, but the only way I can think to do that would be to have a scheduled process that runs every 10 seconds (or some time that you specify). When a user clicks the button, you would add a record to the DB for the time they clicked it and a flag to indicate it had not been completed. Then every 10 seconds when the process runs, check the DB for any unprocessed records and "process them" and update the completed flag accordingly. From the user perspective you can always display the time to execute based on the timestamp that was added to the DB.
  15. That's not a valid comparison. There is logic within the PHP engine to know what to do with the asterisk symbol. It was purpose built to do multiplication. If it did not exist and you wanted to be able to multiply arbitrary numbers you would have to build a function. For example, if the PHP engine knew how to add, but not to multiple here would be one way: function product ($a, $b) { $product = 0; for ($i=0; $i<$a; $i++) { $product += $b; } return $product; } Using the asterisk is kind of like calling an internal function to do the multiplication. For your purposes, you can create a function to do what you need and call that function as a single line. outputDirectory($rootDirectroy); Your logic of a single line is the simplest solution is predicated on the assumption that there is a purpose built function for your needs. If not, one needs to be created. And, I will take readable, multi-line code over condensed code every time. It's a pain to go back to some old code that needs to be refactored and trying to decipher some complicated process that was condensed down to a few lines trying to figure out how it works. Give me separate lines for each step in the process with comments on what it is expected to do.
  16. I would add the following suggestion regarding this type of logic if ($row['fk_usertypes_id'] ==1) { echo "Hello 1"; } else { echo "Hello 2"; } Just because the value is not 1, you should not assume the value is 2 - even if those are the only expected values. I've seen multiple production issues where such logic was implemented and unexpected conditions caused impactful bugs. If you only expect the value to be 1 or 2, I would do the following. if ($row['fk_usertypes_id'] == 1) { echo "Hello 1"; } else if (($row['fk_usertypes_id'] == 2) { echo "Hello 2"; } else { //Throw error echo "Unhandled error"; } Although at this point a switch() statement might make more sense.
  17. A couple things. First please put code into code tags using the forum editor. I have fixed your initial post. Second, you say that you get a "blank screen", but you have provided no content of what debugging you have performed. You state you are looking for another way to iterate over the files - but you have already confirmed that the files do load and you can iterate over them - you just aren't getting results. So, rather than finding a different way to get the files (which you have already accomplished), you need to figure out why it is not working. I suspect the issue may be your variable names are causing confusion and you aren't passing what you think you are to the processing code. In example you post with a single file you have this: $file = file('myfile.xml'); In that case $file is an array of the contents of the file. Then you state that you tried thing such as $file = glob("directory/*"); foreach ($file as $line) { or $directory = 'directory'; $files = scandir($directory); foreach ($files as $file) { In the first case $line is a $file (not a line) and in the second case $file (in the foreach loop) is a reference to the file NOT an array of the contents of the file. I'm assuming you are not calling file() on the file reference within your loop. If you had called that first variable $linesAry, which is more accurate to what it is, I think you would have seen this yourself. This should work. Note I don't have a an environment to test on at the moment. So there could be some minor typos\errors. <?php //Make the DB connection $servername = "localhost"; $username = "dbuser"; $password = "dbpass"; $db = "dbdb"; $conn = new mysqli($servername, $username, $password, $db); if ($conn->connect_error){ die("Connection failed: ". $conn->connect_error); } //Get the contents of the directory $directoryStr = "directory/*"; echo "Processing directory: {$directoryStr}<br>\n"; $filesAry = glob($directoryStr); echo "Found: " . count($filesAry) . " files<br><br>\n"; //Iterate over each file foreach ($filesAry as $fileStr) { //Reset the variables for the data being searched $ip = ''; $hostname = ''; $port = ''; $portArray = array(); $portList = ''; $timestamp = ''; //Get content of the file into an array echo "Processing file: {$fileStr}<br>\n"; $linesAry = file($fileStr); //Iterate over each line of text in the file foreach($linesAry as $lineStr) { //Get IP Address if (strpos($lineStr, 'addrtype="ipv4"') == TRUE) { preg_match('/addr=".* addrtype/', $lineStr, $results); $ip = implode(" ",$results); $ip = ltrim($ip, 'addr="'); $ip = rtrim($ip, '" addrtype'); echo "<br><strong><u>Device</u></strong><br>"; echo "IP Address: $ip<br>"; } //Get Hostname if (strpos($lineStr, 'type="PTR"') == TRUE) { preg_match('/name=".*" type/',$lineStr,$results); $hostname = implode(" ",$results); $hostname = ltrim($hostname,'name="'); $hostname = rtrim($hostname, ' type'); $hostname = rtrim($hostname, '"'); echo "Hostname: $hostname<br>"; } //Get Ports if (strpos($lineStr, 'portid="') == TRUE) { preg_match('/portid=".*><state/',$lineStr,$results); $port = implode(" ",$results); $port = ltrim($port,'portid="'); $port = rtrim($port, '"><state'); echo "Port: $port<br>"; array_push($portArray, $port); } //Add Values to Database if (strpos($lineStr, '/host>') == TRUE) { $timestamp = time(); $mytime = new \DateTimeImmutable('@'.$timestamp); $portList = implode(", ",$portArray); $sql = "insert into _____ (ip,hostname,ports,timestamp) values ('$ip', '$hostname', '$portList', '$timestamp')"; if ($conn->query($sql) === TRUE) { echo "Data Added: $ip - $hostname - $portList - $timestamp <br>"; } else { echo "Error: ".$sql."<br>".$conn->error; } } } } //Close the DB connection $conn->close(); ?>
  18. The previous posters provided some good input and identified the issue - but maybe not as directly as it could be. The issue is that you do not provide the input field a name, i.e. name="clientSearch" or something like that function client_search(){ echo "<h1 color=#00000>Client Search</h1>"; echo "<label for='clientSearch'>Search Clients:</label>"; echo "<input type='text' id='clientSearch' oninput='getSuggestions(this.value)'>"; //What is the name of this field??? echo "<div id='suggestions'></div>"; } But, they are also correct that the organization of the code is problematic. I see no reason to create a function for creating that form field. I am big on writing code one and reusing it (that's assuming you use this field in multiple places) - but in the case of a field within a form it makes it difficult to "see" the entire form. Also, whenever I'm trying to debug issues with data passed from a form, I'll simply output the contents of $_POST or $_GET to the page.
  19. $earliestDateTs = false; foreach($data as $line) { $dateStr = substr($line, 0, 10); //Get just the date part of the string $dateTs = strtotime($dateStr); //Convert the date string to a timestamp if(!$earliestDateTs) { $earliestDateTs = $dateTs; } //If earliestDateTs not set (i.e. first iteration) set to this line's timestamp $earliestDateTs = min($dateTs, $earliestDateTs); //Set earliestDateTs to the minimum of the current value or this line's timestamp } echo "Earliest date: " . date('m/d/Y', $earliestDateTs);
  20. I will second this. I've been involved in the creation of several cloud based applications (browser, mobile apps, and desktop clients) for a commercial company. In my experience, native mobile apps are a pain for many reasons. For Apple apps there was a significant process to get approved to get the app on the iStore. Trying to verify compatibility between different mobile OSes and version was a huge pain. It's "different" from the browser version (assuming Product decided to make the same functionality available in a browser). So the front-end has to be coded and tested separately. And many others. It takes a little more though to design a responsive web application that will display appropriately on a mobile device vs a tablet vs a full size display. But, that extra work is benefitted by having a single application that can be repurposed across multiple devices. I just don't know why so many companies want to build mobile apps that could be served by a responsive web application. Of course, some functions require a mobile app (at least for usability), e.g. if the app needs to interact with data on the mobile device.
  21. You are defining those input fields as arrays. Note the "[]" at the end of the field name. <input type="checkbox" name="tam[]" value="tamzamanli" /> <span style="color: #fdb43f;"> Tam Zamanlı</span> <br /> <input type="checkbox" name="tam[]" value="yarizamanli" /> <span style="color: #fdb43f;"> Yarı Zamanlı</span> Is your intent to allow the user to select multiple options for the "tam" value? If so, this is a valid approach - but the results ill be passed as an array because of the "[]" in the field names. Checkboxes are unique in that if you don't check them - then there is no value passed when the form is submitted. Using the above logic, the first value checked would be passed as "$_POST['tam'][0]", the second one as "$_POST['tam'][1]", etc. So, you would need to write your logic to process that data accordingly. One way you could handle this is by imploding the array into a single string. But, not knowing all the ways you may need to use this data, I can't say if that is the best approach. Also, in your validation part of the script, you can check that $_POST['tam'] isset() and also check that its length is greater than 0: if(count($_POST['tam'])>) then . . . $tamValues = implode(', ', $_POST['tam']); echo "Selected tam values: " . $tamValues; //Assuming "tamzamanli" and "yarizamanli" were checked the output would be: // Selected tam values: tamzamanli, yarizamanli However, if your intent is that the user should only select one of the values for "tam" (and the similar inputs), then you should use a radio group instead. Using a radio group, each element will have the same name and only one record can be selected. You don't need to format the name as an array (but could be for other uses cases not related to your purpose). <input type="radio" name="tam" value="tamzamanli" /> <span style="color: #fdb43f;"> Tam Zamanlı</span> <br /> <input type="radio" name="tam" value="yarizamanli" /> <span style="color: #fdb43f;"> Yarı Zamanlı</span>
  22. A "tiny URL" typically refers to a 3rd party service that will accept a full/long URL and then provide a coded URL for a person to then use for communicating the IRL to people. Typically when in printed format since long URLs can be embedded in links for any digital communications. When those links are utilized, they are first directed to the 3rd party site, which then checks the "tiny URL" parameters to what is stored in their DB and then redirects the user to the intended original URL. Are you wanting code that will utilize a third party service to generate the tiny URLs or are you wanting to build your own tiny URL service? If the former, you would need to check those services and find one that allows for such external submissions. I would suspect they would have instructions for doing so if it is within their TOS. If you want to build your own, what have you done so far and where are you stuck? This is a "help" forum, not a do it for me forum.
  23. If you are wanting to change images - that might be very easy. If you can load a page where the image you want to change is displayed, you can just right-click on the image and select an option to see properties of the image where that image "lives" on the web server. E.g. in Chrome you can select "Open image in new tab" or "Inspect". For many websites, the path you can see in either of those would show you were the image is located on the webserver. However, some web applications might have a src for images that goes through some intermediate process to pull the image based on a parameter (e.g. something like "loadimage.php?img_id=5"). If that's the case, then you can open the php file the image src points to and try to decipher the logic on how it gets the image. One word of caution though, an image could be used in multiple places. If you are only intending to change it in one place it would also change it for any other locations you are unaware of. As for text, it is not as simple. Typically the content is "built" from many different files (as you've see by inspecting the index.php and trying to trace through the files that are called). If the text for a particular page is hard-coded within a file, you can use an IDE (or even robust file search tools) to search all the files in the repository for certain words/phrases within the content to see what files have that content. If the content is in a database, then you would have to figure out what tables(s) the content is stored in and search them for the content. however, if the content is within a database, I would think there would be an "admin" area of the site in order to update the content.
  24. Try this newent = newent.toUpperCase();
  25. Yeah, that was my revised query I sent to him and I can see why it is confusing. While it as not what I would ideally write it should work for him. Based on what I deduced from his code there is a transaction table and a candidates table. A transaction ID will be included in any transaction record created. Then, when that transaction ID is "USED" it will be included (or updated) in a record within the candidates table. The functionality he is trying to create is to identify if: Does the transaction ID exist Has the transaction ID been used That query will take the supplied ID from the form input and pull the transaction ID from both the transition table and the candidates table using a LEFT join. So, if the transaction ID does not exist (within the transaction table) then no records will be returned. If a record is returned, then the logic just needs to check the transaction ID from the Candidates table. If NULL then the transaction code has not been used. I probably would have pulled something like the candidate ID from the candidates table to check (or use a calculated group by to return a 0 or 1 value. But, I had no visibility of any other field names from that table and was too lazy to ask or provide an explanation when using some mock field name for him to change.
×
×
  • 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.