Jump to content

DanRz

Members
  • Posts

    22
  • Joined

  • Last visited

Posts posted by DanRz

  1. Hi All,

    I am terrible at regex.

    I have the following code, which works fine for number such as 123456M...

    if(!preg_match('/[1-9]\d{5}M/', $explode[1])) {
    	throw new RuntimeException('Error: Membership number invalid. Please try again.');
    }

    However, I also need to accept number such as TMP1 and TMP1000 - essentially TMP followed by up to 5 numbers...

    How would I add this too...

    I need it to error if it doesn't match any of the two types.

    Thanks

  2. Hey,

    I am developing an small app that will add data to a mySQL database. This is working fine however, I need to encrypt the data. I have the code to do this; however, I am not sure how people structure the mySQL tables for this?

    Obviously, something like varchar(255) might not be long enough. So do you set all columns to be TEXT?

    Is there a better way of doing this?

    Thanks
    Dan

  3. Hi,

    I have the following expression but it doesn't work as I wish it to...

    [1-9]\d{5}M

    I need any 6 numbers followed by an M.... however, it can be any 5 numbers followed by an M... for example

    123456M = Valid
    1234M = Valid

    But...
    123445 = Invalid
    RANDOM = Invalid

    Thanks

  4. Hey,

    I have the following script that looks to make an excel document using PHPSpreadsheet... the script works great, but it doesn't apply the password to the workbook... what am I missing?

    use PhpOffice\PhpSpreadsheet\Spreadsheet;
    use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
    // Information
    $arrayData[] = array('cells');
    
    // Make File Name
    $filename = 'file-'.time().'.xlsx';
    
    $spreadsheet = new Spreadsheet();
    
    $spreadsheet->getActiveSheet()->getProtection()->setSheet(true);
    $security = $spreadsheet->getSecurity();
    $security->setLockWindows(true);
    $security->setLockStructure(true);
    $security->setWorkbookPassword("PhpSpreadsheet");
    
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->setCellValue('A1', 'Report Generated '. date(DATE_FORMAT_LONG));
    $sheet->fromArray($arrayData, NULL, 'A3');
    
    header('Content-Disposition: attachment;filename='.$filename);
    
    $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
    $writer->save('php://output');

    Thanks

    Dan

  5. Hey,

    I have the following jQuery line... it gets the object noteInfo and displays it into a modal. Works great! However, it doesn't seem to output the line breaks, I just get a big chunk of text. Any ideas would be amazing.

    jQuery Line

    $("#viewNoteModal .modal-body").html(obj.noteInfo);

    Console output

    noteInfo: "This is a note\r↵Sent: 26 September 2022 12:56"

    Dan

     

    EDIT - I have worked this out. It was a bug in the code that outputted the text.

  6. Thanks for your reply. I have managed to fix this :) see code below;

    on:
      push:
        branches: [ development ]
    name: 🚀 Deploy app on new tag
    jobs:
      web-deploy:
        name: 🎉 Deploy
        runs-on: ubuntu-latest
        steps:
        - name: 🚚 Get latest code
          uses: actions/checkout@v3
    
        - name: 🏷️ Get Current Tag
          id: vars
          run:  echo "tag=${GITHUB_REF#refs/*/}" >> $GITHUB_OUTPUT
    
        - name: 🔏 Write Tag Version
          env:
            RELEASE_VERSION: ${{ steps.vars.outputs.tag }}
          run: |
            echo $RELEASE_VERSION
    
        - name: 🗃️ Make env File
          uses: SpicyPizza/create-envfile@v1.3
          with:
            envkey_APP_ENV: "live"
            envkey_APP_STATUS: "1"
            envkey_APP_VERSION: ${{ steps.vars.outputs.tag }}
    
        - name: 📂 Sync files
          uses: SamKirkland/FTP-Deploy-Action@4.3.3
          with:
            server: FTPSERVER
            username: USERNAME
            password: ${{ secrets.ftp_pwd }}

     

  7. Hey!

    I am using the following GitHub workflow to publish to FTP when a new tag is pushed however I need to alter it to get the tag name and update the .env file on the server with the new version... I just can't work out how to do it...

    on:
      push:
        tags:
        - '*'
    name: 🚀 Deploy app on new tag
    jobs:
      web-deploy:
        name: 🎉 Deploy
        runs-on: ubuntu-latest
        steps:
        - name: 🚚 Get latest code
          uses: actions/checkout@v3
    
        - name: 📂 Sync files
          uses: SamKirkland/FTP-Deploy-Action@4.3.3
          with:
            server: ftp.domain.com
            username: XXX
            password: ${{ secrets.ftp_pwd }}
    
        - name: 🔐 Set Env Version
          id: vars
          run: echo "tag=${GITHUB_REF#refs/*/}" >> $GITHUB_OUTPUT
        - name: 🔏 Write Env Version
          env:
            RELEASE_VERSION: ${{ steps.vars.outputs.tag }}
          run: |
            echo $RELEASE_VERSION
            echo ${{ steps.vars.outputs.tag }}

    Any help would be appreciated.

    Dan

  8. 23 hours ago, Barand said:

    sleep() , perchance to dream.

    Thanks, I was thinking sleep but I've had problems with that in the past...

    20 hours ago, mac_gyver said:

    at one per second, it will take 25 minutes to send all the emails. php scripts are not intended to run continuously. you would need to call set_time_limit(...) inside the loop to keep the script from fatally timing out and halting, but not using set_time_limit(0) so as to not prevent the script from stopping due to a programming mistake.

    this is normally done by queuing, in a database table, all the mail addresses to be sent to. having a cron job/scheduled task that runs at some reasonable interval, such as once a minute. the code that the cron job triggers checks if the queue has any unsent messages in it, loops, with a sleep() call inside the loop, to send fewer emails than the time to the next execution of the cron job, to prevent overlap, and marks each email in the queue as having been sent. e.g. with the datetime when it was sent.

    doing this, you would send ~50 email per minute, in 30 executions of the cron job.

    Hmmm I think this might be the way forward... I shall do it like this :)

    19 hours ago, requinix said:

    1 message per second is what they give you in the sandbox. If you're using this for real messages then you should not be in the sandbox...

    Ahh yes, they gave me something like 150,000 emails per day, however, my access keys were leaked and used to send 50,000 odd emails.... so I asked them to move my limit down to 5000 per day as I would never send over that so if it ever happened again I would get stung...

    Thanks

  9. Hey!

    I am trying to write a script that will send emails to users using Amazon SES, I have a send limit of 1 per second...

    Currently I have 1500 records... how would I throttle the script to only send 1 email per second?

    Currently, I just use a foreach loop to go through an array and send the email using that...

    $allActiveMembers = $this->getAllMembers('1');
    foreach($allActiveMembers as $member){
    	// If email blank... skip.
    	if($member['memberEmail'] == NULL){
    		continue;
    	}
    
        // Email Valid.
    	if($this->helper->isValidEmail($member['memberEmail']) == false){
        	continue;
        }
    
        // Send Email
        $this->SendMail($member['memberEmail']);
    
    }

    Thanks

    Dan

  10. Hey!

    I updated my server from PHP 7.4 to PHP 8.1... I have several website on the server and all are now showing some sort of error or another... Most of the errors are warnings such as:

    Quote

    Warning: Attempt to read property "current" on bool in /www/wwwroot/site.com/wp-admin/update-core.php on line 41

    I have changed the php.ini file for 8.1 to exclude warnings bit it doesn't seem to do anything...

    Any idea how to stop them from coming up without having to add

    error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);

     to every website...,

    Thanks
    Dan

  11. 18 hours ago, kicken said:

    Try browsing directly to your .env file on your website, for example http://example.com/.env and see if the file contents comes up.  If it does, then that's your problem.

    Ideally you'd store your .env file outside of your webroot so it's inaccessible via any URL.  If you're hosting provider does not allow for that, then you need to configure the webserver to not allow access to your .env file via .htaccess or some similar mechanism.  If you can't do that, then the next best option is to store the credentials as PHP code in a .php file so even if someone does try and load the URL they won't see the PHP code.

     

    Thanks so much! I never thought of this bit that indeed was the problem... an oversight I think!!

    I have now secured it with htaccess so its Forbidden now.

    Thanks for your help!

  12. I have a php application I made…

    Currently I use phpdotenv https://github.com/vlucas/phpdotenv to store my creds in a .env file in the root directory…

    It works, however twice now the AWS SES creds have been stolen and used to send mass emails…

    Im not sure how they’re finding the information but they are… so I’m just trying to figure out how to store them better to avoid them getting into the wrong hands…

  13. Hey!

    So for years I used to use Dreamweaver, then about 5 years ago changed to Coda for MacOS and only 2 years ago changed to Atom by GitHub and absolutely love Atom. However, they announced from 15 December 2022 that they would be closing down Atom... sad I know :(

    Find out more here - https://github.blog/2022-06-08-sunsetting-atom/

    Anyway... I need to find myself a new code editor... question is what do you use? I am based on Mac so need to have one that's compatible with that!!

    Dan

  14. Try this...

    <?php
    //It's a simple program to valid age but it only print 'you can vote' despite any value I input.
    if($_POST['age']){
      $age = int $_POST['age'];
    
      if($age >= 18){
        echo "you can vote!!!";
      }elseif($age < 18){
        echo "You are not allowed to vote";
      }else{
        echo "enter a valid age";
      }
    }
    ?>

     

    Also on your form use this instead... it means the user can only put a number in...

    <input type="number" name="age">

     

  15. Hey,

    Sorry yes I thought about this after I posted... so the file is an excel file and the array returned from 

    $this->memberImporterDataSorter($rows)

    is as follows... the uniqueness of this is the memberNumber which is how you know who is who...

    Array
    			(
    			    [0] => Array
    			        (
    			            [memberNotes] => 
    			            [memberNumber] => 123456L
    			            [memberName] => Jim Jones
    			            [memberAddress] => 
    			            [memberEmail] => 
    			            [memberCommsEmail] => 1
    			            [memberLocation] => 1
    			            [memberArea] => 4
    			            [memberLocationTxt] => 
    			            [memberAreaTxt] => 
    			            [memberJob] => 3
    			            [memberJobTxt] => 
    			            [memberCommsSMS] => 1
    			            [memberTel] => 
    			            [memberJoined] => 1644192000
    			            [lastUpdateUnion] => 1666998000
    			        )
    
    			    [1] => Array
    			        (
    			            [memberNotes] => 
    			            [memberNumber] => 112233L
    			            [memberName] => Jennifer Zoom
    			            [memberAddress] => 
    			            [memberEmail] => 
    			            [memberCommsEmail] => 1
    			            [memberLocation] => 1
    			            [memberArea] => 4
    			            [memberLocationTxt] => 
    			            [memberAreaTxt] => 
    			            [memberJob] => 99
    			            [memberJobTxt] => 
    			            [memberCommsSMS] => 1
    			            [memberTel] => 
    			            [memberJoined] => 1599692400
    			            [lastUpdateUnion] => 1665442800
    			        )
    						)

    Here is the actual importer code;

    set_time_limit(3600);
    		try {
    			if(!file_exists($filePath)){
    				throw new \Exception("Hmm... Import file can't be found. Please try again.");
    			}
    
    			// Read the Excel and pop into an array
    			$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($filePath);
    			$worksheet = $spreadsheet->getActiveSheet();
    
    			$rows = [];
    			foreach ($worksheet->getRowIterator() AS $row) {
    					$cellIterator = $row->getCellIterator();
    					$cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells,
    					$cells = [];
    					foreach ($cellIterator as $cell) {
    							$cells[] = $cell->getFormattedValue();
    					}
    					$rows[] = $cells;
    			}
    
    			// Pop the first array item off, not needed
    			array_shift($rows);
    
    			// Sort the data
    			$rows = $this->memberImporterDataSorter($rows);
    
    			// Set blank core array
    			$coreImportArray = array(
    				"addedMembers" => array(),
    				"leftMembersAfter" => array(),
    				"rejoinedMembers"	=>	array()
    			);
    
    			// Get Total Cancelled Before Import
    			$returnData = $this->database->getAll("SELECT * FROM `members` WHERE `memberStatus` = '2';", array());
    			$coreImportArray['totalCancelledBefore'] = count($returnData);
    
    			// Decode
    			$returnData = $this->encryption->decode_data($returnData, array("memberName","memberAddress","memberEmail","memberTel","memberNotes"));
    
    			// Add left members to array
    			foreach($returnData as $left){
    				$coreImportArray['leftMembersBefore'][$left['memberNumber']] = array("memberNumber" => $left['memberNumber'],"memberName" => $left['memberName'],"memberArea" => $left['memberArea']);
    			}
    
    			// First Set all users to canclled (status 2)
    			$this->database->execute("UPDATE `members` SET `memberStatus` = '2', `memberLeft` = ? WHERE `memberStatus` = '1';", array(time()));
    
    			// Run each line of data and process the import
    			foreach($rows as $memberData){
    				// If member number empty continue...
    				if($memberData['memberNumber'] == NULL){
    					continue;
    				}
    
    				// Check if member exists in DB
    				$checkExists = $this->database->countRows("SELECT * FROM `members` WHERE `memberNumber` = ?;", array($memberData['memberNumber']));
    
    				if($checkExists == '1'){
    					// They exist, update data and status 1
    					$this->database->execute("UPDATE `members` SET `memberStatus` = '1', `memberLeft` = NULL, `memberLeftReason` = NULL WHERE `memberNumber` = ?;", array($memberData['memberNumber']));
    				}else{
    					// Encode Data
    					$memberDataEnc = $this->encryption->encode_data_single($memberData, array("memberName","memberAddress","memberEmail","memberTel","memberNotes"));
    
    					// New Member! Insert them...
    					$this->database->execute("INSERT INTO `members` (`memberNumber`, `memberName`) VALUES (?,?);", array($memberDataEnc['memberNumber'], $memberDataEnc['memberName']));
    					$lastID = $this->database->getLastId();
    
    					// Add new member to new members array :)
    					$coreImportArray['addedMembers'][$memberData['memberName']] = array(
    								"id" => $lastID,
    								"memberName" => $memberData['memberName'],
    								"memberNumber" => $memberData['memberNumber'],
    								"memberArea" => $memberData['memberArea']
    							);
    				}
    			}
    
    			// Run analysis
    			// Total Cancelled After Import
    			$returnData = $this->database->getAll("SELECT * FROM `members` WHERE `memberStatus` = '2';", array());
    			$coreImportArray['totalCancelledAfter'] = count($returnData);
    			$returnData = $this->encryption->decode_data($returnData, array("memberName","memberAddress","memberEmail","memberTel","memberNotes"));
    			foreach($returnData as $left){
    				if($coreImportArray['leftMembersBefore'][$left['memberName']]['memberNumber'] != $left['memberNumber']){
    					$coreImportArray['leftMembersAfter'][$left['memberName']] = array("memberNumber" => $left['memberNumber'],"memberName" => $left['memberName'],"memberArea" => $left['memberArea']);
    				}
    			}
    			unset($coreImportArray['leftMembersBefore']);
    
    			// Update Stats
    			$coreImportArray['totalNew'] = count($coreImportArray['addedMembers']);
    			$coreImportArray['totalLeft'] = $coreImportArray['totalCancelledAfter'] - $coreImportArray['totalCancelledBefore'];
    			if($coreImportArray['totalNew'] < 0){ $coreImportArray['totalNew'] = 0; }
    			if($coreImportArray['totalLeft'] < 0){ $coreImportArray['totalLeft'] = 0; }
    			if($coreImportArray['totalCancelledAfter'] < $coreImportArray['totalCancelledBefore']){
    				$coreImportArray['totalRejoined'] = $coreImportArray['totalCancelledBefore'] - $coreImportArray['totalCancelledAfter'];
    			}else{
    				$coreImportArray['totalRejoined'] = 0;
    			}
    
    			// Count Arrays
    			$coreImportArray['joinersCount'] = count($coreImportArray['newMembers']);
    			$coreImportArray['leaversCount'] = count($coreImportArray['newLeavers']);
    			$coreImportArray['rejoinCount'] = count($coreImportArray['newRejoin']);
    
    			return $coreImportArray;
    
    		} catch (\Exception $e){
    			// Display error...
    			$this->helper->set_message($this->helper->validation_errors($e->getMessage()));
    		}

    There is probably a much easier way to achieve what I am after so any help would be appreciated.

    Basically the data is from an external source, so I need to loop through the new data from excel. 

    If they are NOT already in the database add them, if they are in the database but cancelled, reactive them and anyone who's in the database but NOT on the excel sheet will be cancelled.

    Thanks

  16. Hey!

    I am writing a script however, I am a little stuck with the logic for import... here is the background...

    I have a database of users, some are active some are inactive.

    I have a new array to import, however, in this array people could be one of the following:

    New User - Add to database
    New User with Existing Account - Rejoin them
    Left User - User ID not found in the new array so assume they have left...

    I need to process the data and output the following;

    Number of New Users
    Number of Users Rejoined
    Number of Users Left
    List of New User IDs
    List of Left User IDs
    List of Rejoined User IDs

    I have written a script, however it doesn't work well and gives me random information that doesn't match so the logic is off somewhere.. can someone help with the logic

    Currently it does the following:

    1. Counts the current users who are marked as inactive
    2. Makes an array of those users
    3. Sets all database users to inactive
    4. Loops though each new user from import array
    5. If user ID exists... update the user to active again
    6. If user ID doesn't exist... add them to the database and add new user ID to new array
    7. Counts all users who are marked as inactive after import
    8. Use array_diff_key to check the difference between inactive array 1 (before import) and array 2 (after import)
    9. Counts number of array items for joiners, and leavers...

    I hope this makes at least some sense... any help would be appreciated.

    Thanks
    Dan

  17. Hey!

    I have the following code in a class..

    public function deductCredit(){
    		$currentAmount = $this->getCredits();
    		$newAmount = $currentAmount - '1';
    		$this->dashboard->updateSettings("email_credit", array("count"=>$newAmount));
    		return $newAmount;
      }

    This gets the current credits... deducts 1 and pushes the update back...

    If I run the function outside of the class it works as expected... however, if I run it within a functions a bit further down the class it always returns -1...

    Any ideas would be appreciated!

    Dan

×
×
  • 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.