Pages

Thursday, September 14, 2023

Download Multiple Files from Array of Links using PHP CURL

 <?php


// List of URLs to download

$urls = [

    'https://example.com/file1.zip',

    'https://example.com/file2.pdf',

    'https://example.com/file3.txt',

]


// Destination directory to save the downloaded files

$destinationDir = 'downloads/';

$directory = 'downloads/';

foreach (glob($directory . "*.mp3") as $filename) {

    $file = realpath($filename);

    $newFilename = urldecode($file);

    if ($newFilename !== $file) {

        rename($file, $newFilename);

        echo 'Renamed ' . $file . ' to ' . $newFilename . PHP_EOL;

    }

}

// Create the destination directory if it doesn't exist

if (!is_dir($destinationDir)) {

    mkdir($destinationDir, 0777, true);

}


// Iterate over each URL and download the file

foreach ($urls as $url) {

    // Extract the filename from the URL

    $filename = basename($url);


    // Encode the filename to handle special characters

    $encodedFilename = urlencode($filename);


    // Set the destination path for the downloaded file

    $destinationPath = $destinationDir . $encodedFilename;


    // Initialize cURL session

    $curl = curl_init($url);


    // Set the option to return the response as a string

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);


    // Execute the cURL session and store the response

    $response = curl_exec($curl);


    // Check if any error occurred during the request

    if (curl_errno($curl)) {

        echo 'Error downloading ' . $url . ': ' . curl_error($curl) . PHP_EOL;

    } else {

        // Save the response to the destination file

        file_put_contents($destinationPath, $response);

        echo 'Downloaded ' . $url . ' to ' . $destinationPath . PHP_EOL;

    }

    // Close the cURL session

    curl_close($curl);

}

show time in human difference time in custom php function

function time_elapsed_string($datetime, $full = false) {

            $now = new DateTime;

            $ago = new DateTime($datetime);

            $diff = $now->diff($ago);

            $diff->w = floor($diff->d / 7);
            $diff->d -= $diff->w * 7;

            $string = array(

                'y' => 'year',

                'm' => 'month',

                'w' => 'week',

                'd' => 'day',

                'h' => 'hour',

                'i' => 'minute',

                's' => 'second',

            );

            foreach ($string as $k => &$v) {

                if ($diff->$k) {

                    $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');

                } else {

                    unset($string[$k]);

                }

            }

            if (!$full) $string = array_slice($string, 0, 1);

            return $string ? implode(', ', $string) . ' ago' : 'just now';

        }

// show time in human difference time in custom php function

<?php echo  time_elapsed_string($key['date_created'], true); ?>

Tuesday, May 9, 2023

How to exclude databases while importing a MySQL backup file

Introduction:

If you need to import a MySQL backup file that contains multiple databases, you may want to exclude some of the existing databases from being overwritten. In this tutorial, we will show you how to exclude specific databases while importing a MySQL backup file using a bash script.

Prerequisites:

Basic knowledge of bash scripting

Access to a command-line interface

A MySQL database backup file (.sql extension)

Steps:

1. Create a new bash script file and open it using a text editor of your choice.

2. Add the following code to the file:

bash
#!/bin/bash 
echo "Enter MySQL username: "
read -s USERNAME
echo "Enter MySQL password: "
read -s PASSWORD
echo "Enter MySQL host (default: localhost): "
read HOST 
if [ -z "$HOST" ]; 
  then HOST="localhost"
fi 
echo "Enter path to backup file (e.g. /path/to/backup.sql): "
read BACKUP_PATH
if [ ! -f "$BACKUP_PATH" ];
then
  echo "File not found: $BACKUP_PATH"
  exit 1
fi 
 DATABASES=$(mysql --user="$USERNAME" --password="$PASSWORD" --host="$HOST" -e "SHOW DATABASES;" | grep -Ev "(Database|information_schema|mysql|mytinerycms|performance_schema|sys)")

for
db in $DATABASES
do
 DB_ARGS+=(
"--database" "$db")
done 
 mysql --user="$USERNAME" --password="$PASSWORD" --host="$HOST" "${DB_ARGS[@]}" < "$BACKUP_PATH"

3. Save the file with a name such as mysql-import.sh.
4. Open a terminal or command prompt and navigate to the directory where you saved the script.
5. Make the script executable by running the following command:

chmod +x mysql-import.sh

7. When prompted, enter your MySQL username and password. If your MySQL server is running on a different host than localhost, enter the hostname as well.
8. Enter the path to the backup file when prompted.
9. The script will exclude the following databases from the import: information_schema, mysql, mytinerycms, performance_schema, sys. All other databases will be included.
10. The script will import the backup file to the specified MySQL server.

Conclusion:
In this tutorial, we showed you how to exclude specific databases while importing a MySQL backup file using a bash script. By modifying the script, you can exclude any database from the import by adding its name to the exclusion list. This is a simple and effective way to prevent overwriting existing databases while importing backups.








Saturday, December 31, 2022

Laravel .htacess for setting root as working directory

 <IfModule mod_rewrite.c>

       RewriteEngine On

       RewriteRule ^(.*)$ public/$1 [L]

    </IfModule>


React app build .htaccess for live server

 <IfModule mod_rewrite.c>


  RewriteEngine On

  RewriteBase /

  RewriteRule ^index\.html$ - [L]

  RewriteCond %{REQUEST_FILENAME} !-f

  RewriteCond %{REQUEST_FILENAME} !-d

  RewriteCond %{REQUEST_FILENAME} !-l

  RewriteRule . /index.html [L]


</IfModule>

Friday, November 5, 2021

Update User password in firebase and update data in firebase table

<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-app.js"></script>

<!--   TODO: Add SDKs for Firebase products that you want to use https://firebase.google.com/docs/web/setup#available-libraries   -->

<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-analytics.js"></script>

<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-auth.js"></script>

<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-database.js"></script>


<scipt>

const firebaseConfig = {

    apiKey: "APIKEY",

    authDomain: "my-project-ID.firebaseapp.com",

    projectId: "my-project-ID",

    storageBucket: "my-project-ID.appspot.com",

    messagingSenderId: "messagingSenderID",

    appId: "1:APIID",

    measurementId: "MEASUREMENT-ID",

    databaseURL: "https://my-project-ID-default-rtdb.firebaseio.com/",

  };

</scipt>


<script>

var New_Password = "test123";

const user = firebase.auth().currentUser;

              user.updatePassword(New_Password).then(() => {

                alert("successfully updated password");

              }).catch(function (error) {

                alert("failed"+ error.message);

              }); 

/********** UPDATE USER DATA ***********/

$("#updateUserData").on('click', function (e) {

  e.preventDefault();

  var firstName = $("#First-Name-Account").val();

  var lastName = $("#Last-Name-Account").val();

  var emailAddress = $("#Email-Account").val();

  var phoneNumber = $("#Phone-Account").val();

  

  let userRef = database.ref('users/' + userId);

  userRef.child(userId).set({

    "firstName": firstName,

    'lastName': lastName,

    'emailAddress': emailAddress,

    'phoneNumber': phoneNumber

  }).then(function() {

    errors = "Profile updated successfully";

    alert(errors);

    // Data saved successfully!

  })

  .catch(function(error) {

    // The write failed...

    errors = error.message;

    alert(errors);

  });

});

</script>

Friday, July 16, 2021

Find and delete all files from current and recursive directory in Linux

https://www.cyberciti.biz/faq/linux-unix-how-to-find-and-remove-files/

find . -type f -name "*youfilename" -print0 | xargs -I {} -0 rm -v "{}"

 

find . -type f -name "*.zip" -print0 | xargs -I {} -0 rm -v "{}"

Sunday, July 11, 2021

UBuntu Database Error: Access denied for user 'root@localhost' (using password:NO)

 
https://stackoverflow.com/questions/2995054/access-denied-for-user-rootlocalhost-using-passwordno

[root ~]# mysql -u root
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password:NO)

sudo mkdir /var/run/mysqld
sudo chown mysql: /var/run/mysqld

sudo mysqld_safe --skip-grant-tables --skip-networking &



1. Stop the service/daemon of mysql running

    [root ~]# service mysql stop   
    mysql stop/waiting

2. Start mysql without any privileges using the following option; This option is used to boot up and do not use the privilege system of MySQL.
    [root ~]# mysqld_safe --skip-grant-tables &

3. enter the mysql command prompt
    [root ~]# mysql -u root
    mysql>

4. Fix the permission setting of the root user ;
    mysql> use mysql;
    Database changed
    mysql> select * from  user;
    Empty set (0.00 sec)
    mysql> truncate table user;
    Query OK, 0 rows affected (0.00 sec)
    mysql> flush privileges;
    Query OK, 0 rows affected (0.01 sec)
    mysql> grant all privileges on *.* to root@localhost identified by 'YourNewPassword' with grant option;
    Query OK, 0 rows affected (0.01 sec)

*if you don`t want any password or rather an empty password
    
    mysql> grant all privileges on *.* to root@localhost identified by '' with grant option;
    Query OK, 0 rows affected (0.01 sec)*
    mysql> flush privileges;
    Query OK, 0 rows affected (0.00 sec)

Confirm the results:
    mysql> select host, user from user;
    +-----------+------+
    | host      | user |
    +-----------+------+
    | localhost | root |
    +-----------+------+
    1 row in set (0.00 sec)

5. Exit the shell and restart mysql in normal mode.
    mysql> quit;
    [root ~]# kill -KILL [PID of mysqld_safe]
    [root ~]# kill -KILL [PID of mysqld]
    [root ~]# service mysql start

6. Now you can successfully login as root user with the password you set
    [root ~]# mysql -u root -pYourNewPassword
     mysql>

Monday, June 21, 2021

Javascript Timer start and end

05 : 00

 

<script>

$(document).ready(function(){

  var timer2 = "05 : 01";

  var interval = setInterval(function() {


    var timer = timer2.split(':');

    //by parsing integer, I avoid all extra string processing

    var minutes = parseInt(timer[0], 10);

    var seconds = parseInt(timer[1], 10);

    --seconds;

    minutes = (seconds < 0) ? --minutes : minutes;

    if (minutes < 0) clearInterval(interval);

    seconds = (seconds < 0) ? 59 : seconds;

    seconds = (seconds < 10) ? '0' + seconds : seconds;

    //minutes = (minutes < 10) ?  minutes : minutes;

    if(minutes == 0 && seconds == 0) {

      console.log(minutes + "  "+ seconds);

      clearInterval(interval);

      localStorage.removeItem('timerstart');

    }

    $('#timerSec').html(minutes + ' : ' + seconds);

    timer2 = minutes + ' : ' + seconds;

  }, 1000);

})

</script>

<strong id="timerSec" class="bold-text">05 : 00</strong>

Forgot Password and reset password in Firebase with custom email template

<div class="div-block-form">

    <div class="statusnotificaiton notificationbox"><strong>Success: </strong>Password reset Email is recevied on your

        email zakeerio25@gmail.com please check your email and reset password.</div>

    <h2 class="heading-pages">Forgot Password?</h2>

    <div class="text-block-pages">Please enter your mobile number and we will send you

        <br>instructions to reset your password

    </div>

    <div class="form-block-page w-form">

        <form id="wf-form-Phone-Form" name="wf-form-Phone-Form" data-name="Phone Form" class="form">

            <div class="div-block-21">

                <label id="label-pass" for="Email" class="field-label-down up">Email</label>

                <input type="email" class="text-field-2 w-input" data-input="2" maxlength="256" name="Email"

                    data-name="Email" id="resetEmail" required="">

            </div>

            <a id="create" href="#" class="submit-button-forgot next-button text-center w-button">Continue</a>

        </form>

    </div>

    <div class="text-block-11">Back to <a href="/login" class="link-3">Login</a></div>

</div>


<script>

    create.addEventListener('click', resetPassword);

    function resetPassword() {

        var auth = firebase.auth();


        var emailAddress = resetEmail.value;

        if (emailAddress == "") {

            $('.statusnotificaiton.notificationbox').html('<strong>Error: </strong> The email field should not be empty!');

            $('.statusnotificaiton.notificationbox').removeClass('statussuccess').addClass("statuserror");

            setTimeout(function () {

                $('.statusnotificaiton.notificationbox').removeClass('statuserror');

            }, 3000)

        } else {

            //http://website.com/forgot-password-reset?mode=resetPassword&oobCode=Abcd&apiKey=12334&lang=en

            auth.sendPasswordResetEmail(emailAddress).then(function (response) {

                console.log(response);

                $('.statusnotificaiton.notificationbox').html('<strong>Success: </strong>Password reset Email is recevied on your email ' + emailAddress + ' please check your email and reset password.');

                $('.statusnotificaiton.notificationbox').removeClass('statuserror').addClass("statussuccess");

                setTimeout(function () {

                    $('.statusnotificaiton.notificationbox').removeClass('statussuccess');

                    //document.location.assign('/login'); 

                }, 3000)

                // Email sent.

            }).catch(function (error) {

                console.log(error.code);

                $('.statusnotificaiton.notificationbox').html('<strong>Error: </strong>' + error.message);

                $('.statusnotificaiton.notificationbox').removeClass('statussuccess').addClass("statuserror");

                setTimeout(function () {

                    $('.statusnotificaiton.notificationbox').removeClass('statuserror');

                }, 3000)

                //errorMessage.innerHTML = error.message;

                //$('.w-form-fail').show();

            });

        }

    }

</script>

https://yourwebsite.com/forgot-password-reset?mode=resetPassword&oobCode=123111&apiKey=APIKEY&lang=en

RESET PASSWORD PAGE

<div class="div-block-form">

    <div class="statusnotificaiton notificationbox">This is test notification here</div>

    <h2 class="heading-pages">Reset Password</h2>

    <div class="text-block-pages-otp">Please input a new password</div>

    <div class="form-block-page-reset w-form">

        <form id="wf-form-Phone-Form" name="wf-form-Phone-Form" data-name="Phone Form" class="form">

            <input type="password" class="text-field-password-reset w-input" autofocus="true" maxlength="256"

                name="New-Password" data-name="New Password" placeholder="New Password" id="New-Password" required="">

            <input type="password" class="text-field-password-reset w-input" autofocus="true" maxlength="256"

                name="New-Password-confirm" data-name="New Password confirm" placeholder="Confirm Password"

                id="New-Password-confirm" required="">

            <input type="submit" value="Submit" data-wait="Please wait..." id="confirmPassword12"

                class="submit-button-forgot next-button d-none w-button"><a id="confirmPassword" href="#"

                class="submit-button-forgot next-button text-center w-button">Continue</a>

        </form>

    </div>

    <div class="text-block-pages-pass">Your password will be used to login and confirm

        <br>transactions the website

    </div>

</div>

<script>

    //document.addEventListener('DOMContentLoaded', () => {

    // TODO: Implement getParameterByName()

    $("#confirmPassword").on('click', function () {

        var pwd = $("#New-Password").val();

        var confirmpwd = $("#New-Password-confirm").val();

        if (pwd != confirmpwd) {

            $('.statusnotificaiton.notificationbox').html("<strong>Error: </strong>The confirm password does not match!");

            $('.statusnotificaiton.notificationbox').removeClass('statussuccess').addClass("statuserror");

            localStorage.removeItem('userdata');

            localStorage.removeItem('photoUrl');

            setTimeout(function () {

                $('.statusnotificaiton.notificationbox').removeClass('statuserror').html("");

            }, 3000)


            return false;


        }

        // Get the action to complete.

        var mode = getParameterByName('mode');

        // Get the one-time code from the query parameter.

        var actionCode = getParameterByName('oobCode');

        // (Optional) Get the continue URL from the query parameter if available.

        var continueUrl = getParameterByName('continueUrl');


        var apiKey = getParameterByName('apiKey');

        // (Optional) Get the language code if available.

        var lang = getParameterByName('lang') || 'en';


        // Configure the Firebase SDK.

        // This is the minimum configuration required for the API to be used.

        var auth = firebase.auth();

        // Handle the user management action.

        switch (mode) {

            case 'resetPassword':

                // Display reset password handler and UI.

                handleResetPassword(auth, actionCode, continueUrl, lang);

                break;

            case 'recoverEmail':

                // Display email recovery handler and UI.

                handleRecoverEmail(auth, actionCode, lang);


                break;

            case 'verifyEmail':

                // Display email verification handler and UI.

                handleVerifyEmail(auth, actionCode, continueUrl, lang);

                break;

            default:

            // Error: invalid mode.

        }

    });

    //}, false);

    function handleResetPassword(auth, actionCode, continueUrl, lang) {

        // Localize the UI to the selected language as determined by the lang

        // parameter.

        // Verify the password reset code is valid.

        auth.verifyPasswordResetCode(actionCode).then((email) => {

            var accountEmail = email;

            console.log(email);

            // TODO: Show the reset screen with the user's email and ask the user for

            // the new password.

            var newPassword = $("#New-Password").val();

            // Save the new password.

            auth.confirmPasswordReset(actionCode, newPassword).then((resp) => {

                // Password reset has been confirmed and new password updated.

                // TODO: Display a link back to the app, or sign-in the user directly

                // if the page belongs to the same domain as the app:

                //auth.signInWithEmailAndPassword(accountEmail, newPassword);

                auth.signInWithEmailAndPassword(accountEmail, newPassword).then((userCredential) => {

                    var user = userCredential.user;

                    useremail = user.email;

                })

                    .catch((error) => {

                        console.log(error.code);

                        errorMessage.innerHTML = error.message;

                        $('.w-form-fail').show();

                    });

                // TODO: If a continue URL is available, display a button which on

                // click redirects the user back to the app via continueUrl with

                // additional state determined from that URL's parameters.

            }).catch((error) => {

                // Error occurred during confirmation. The code might have expired or the

                // password is too weak.

                console.log(error);

                $('.statusnotificaiton.notificationbox').html(error.message);

                $('.statusnotificaiton.notificationbox').removeClass('statussuccess').addClass("statuserror");

                localStorage.removeItem('userdata');

                localStorage.removeItem('photoUrl');

                setTimeout(function () {

                    $('.statusnotificaiton.notificationbox').removeClass('statuserror');

                    removeStorageitems(keysToRemove);

                }, 3000)

            });

        }).catch((error) => {

            // Invalid or expired action code. Ask user to try to reset the password

            // again.

            console.log(error);

            $('.statusnotificaiton.notificationbox').html(error.message);

            $('.statusnotificaiton.notificationbox').removeClass('statussuccess').addClass("statuserror");

            localStorage.removeItem('userdata');

            localStorage.removeItem('photoUrl');

            setTimeout(function () {

                $('.statusnotificaiton.notificationbox').removeClass('statuserror');

                removeStorageitems(keysToRemove);

            }, 3000)

        });

    }

    function getParameterByName(name, url) {

        if (!url) {

            url = window.location.href;

        }

        name = name.replace(/[\[\]]/g, "\\$&");

        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),

            results = regex.exec(url);

        if (!results) return null;

        if (!results[2]) return '';

        return decodeURIComponent(results[2].replace(/\+/g, " "));

    }

</script>

Monday, June 7, 2021

Get the Google places API city, state and Country

 <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>

<script>

var city = document.getElementById("userdata_citystate");

    console.log(city);

    var autocomplete = new google.maps.places.Autocomplete(city);

    autocomplete.addListener('place_changed', function() {

    var place = autocomplete.getPlace();

    var address = place.formatted_address;

            var latitude = place.geometry.location.lat();

            var longitude = place.geometry.location.lng();

            var latlng = new google.maps.LatLng(latitude, longitude);

            var geocoder = geocoder = new google.maps.Geocoder();

            geocoder.geocode({ 'latLng': latlng }, function (results, status) {

                if (status == google.maps.GeocoderStatus.OK) {

                    if (results[0]) {

                        var address = results[0].formatted_address;

                        var state = results[0].address_components[results[0].address_components.length - 3].long_name;

                        var city = results[0].address_components[results[0].address_components.length - 4].long_name;

                        $("#userdata_citystate").val(city+", "+state);

                    }

                }

            });

    

    console.log("You selected: '" + place.formatted_address + "'");

  });

</script>

Monday, May 17, 2021

Share Windows Network Shared Files in Ubuntu(20.04)

===================================================

/*
 *
 * Share files from Windows Operating System TO Ubuntu
 *
 */

===================================================


sudo apt update
sudo apt-get install cifs-utils
sudo mkdir /mnt/winshare

sudo chown -R nobody:nogroup /mnt/winshare
sudo chmod -R 0755 /mnt/winshare

user: windowsusername
pass: userpassword

sudo mount -t cifs -o username=windows_user_account_here //WIN_MACHINE_IP/PublicShares /mnt/winshare

sudo mount -t cifs -o username=am-dev //192.168.00.001/directoryname1 /mnt/winshare/directoryname1
sudo mount -t cifs -o username=am-dev //192.168.00.001/directoryname2 /mnt/winshare/directoryname2

alias winsharedev="sudo mount -t cifs -o username=am-dev //192.168.0.222/ampdevelopment /mnt/winshare/ampdevelopment"
alias winsharevue="sudo mount -t cifs -o username=am-dev //192.168.0.222/vueapp /mnt/winshare/vueapp"

unalias winsharedev
unalias winsharevue


AUTO CONNECT

set Credentials on  a file
sudo nano /etc/win_cred

Windows Network user Credentials

username=windowsusername
password=userpassword
domain=192.168.00.001

Assign user and permissions to file

sudo chown root: /etc/win_cred
sudo chmod 600 /etc/win_cred

mount Network directory  to ubuntu directory /mnt/winshare

sudo mount -t cifs -o credentials=/etc/win_cred WIN_MACHINE_IP/PublicShares /mnt/winshare//

sudo mount -t cifs -o credentials=/etc/win_cred 192.168.00.001/directoryname /mnt/winshare/directoryname/

Tuesday, April 27, 2021

Add days to Date in Javascript


 

 

 

<input id="date" type="text" value="10-12-202" />
<select id="terms" onchange="return dueDate()">
  <option value=""></option>
  <option value="10">10</option>
  <option value="20">20</option>
  <option value="20">20</option>
  <option value="90">90</option>
</select>
<input id="due_date" readonly="" type="text" />

<script>

function dueDate(){
  var terms=parseFloat (document.getElementById("terms").value);

  var inv_date=document.getElementById("date").value;

  var res = inv_date.split("-");
  inv_date = res[2]+"-"+res[1]+"-"+res[0];

  var today =new Date(inv_date);
  var dueDate =new Date(inv_date).setDate(today.getDate()+terms);
  var newDate = new Date(dueDate);
  //alert(newDate);
  //newDate = newDate.toLocaleString();
  var date = newDate.getDate();
  date = (date &lt;= 9) ? '0'+date : date;
  var month = newDate.getMonth()+1;
  month = (month &lt;= 9) ? '0'+month : month;

  var year = newDate.getFullYear();
  //alert(month);
  document.getElementById("due_date").value=date+"-"+month+"-"+year;
}
</script>

Monday, April 19, 2021

Firebase Social Login Authentication in HTML

Firebase Authentication practice