In one of our blog post, we capitalized the string in PHP. In this, we will show you, how you can capitalize the string in Javascript. The code used in this tutorial can be used in any Javascript framework or library like React.js, Vue.js, Angular etc.
The first thing we need to do is to split the string using space.
let str = "adnan afzal"
const parts = str.split(" ") // ["adnan", "afzal"]
split(delimiter): Is a function in Javascript that can be chained on strings. It will split the string into parts using delimiter and return it as an array.
Then we will loop through all parts of that array.
for (let a = 0; a < parts.length; a++) {
// [section-1]
}
After that, we will first convert the first letter of the word to uppercase. Then we will return the remaining letters in that word and concatenate them.
// uppercase first letter
const firstLetter = parts[a][0].toUpperCase()
// return string except for first character (as it is uppercased)
const remainingStr = parts[a].substr(1)
// concatenate both strings
parts[a] = firstLetter + remainingStr
toUpperCase(): A Javascript function that can be called from string and will return the uppercase version of that string.
substr(start): This function can also be called from strings. It will return the remaining string starting from start parameter.
parts[a]: This will get the current word in the iteration. For example “adnan”.
parts[a][0]: This will get the first letter of the current word. For example “a”.
parts[a][0].toUpperCase(): Converts “a” to “A”.
parts[a].substr(1): Returns the string skipping the first character i.e. “dnan”.
Thus concatenating “A” and “dnan”, we get “Adnan”. This will do for each word. The last thing we need to do is to combine all the capitalized words together. Following code goes after the loop.
I created an online free FTP manager in PHP that allows developers to work on their projects from anywhere. I created this tool in PHP and MySQL using Laravel framework. The frontend is designed in Bootstrap and React JS.
Let’s discuss each feature and I will also show you how I built this.
What you will learn:
Connect with FTP.
List files from FTP directory.
Fetch file content.
Edit FTP file.
Create a new file.
Create a new folder.
Upload files.
Download files.
Rename file.
Delete file.
Delete folder.
We created a PHP class named “FTP” in a file called “FTP.php”. All our functions will go in that class.
1. Connect with FTP
The first step is to connect with FTP server. Following code will create a function that will connect with your FTP server (we are not calling it yet).
class FTP
{
private $conn_id = null;
private $server = "";
private $username = "";
private $password = "";
private function do_connect()
{
try
{
// Establishing connection
$this->conn_id = ftp_connect($this->server);
if (!$this->conn_id)
{
echo json_encode([
"status" => "error",
"message" => "Could not connect to " . $this->server
]);
exit();
}
// Login with username and password
$login_result = ftp_login($this->conn_id, $this->username, $this->password);
if (!$login_result)
{
echo json_encode([
"status" => "error",
"message" => "Wrong password for '" . $this->username . "'."
]);
exit();
}
// Enable passive mode for better compatibility
ftp_pasv($this->conn_id, true);
}
catch (\Exception $exp)
{
echo json_encode([
"status" => "error",
"message" => "Could not connect to " . $this->server
]);
exit();
}
}
}
Comments has been added with each line for explanation. Make sure to enter your correct FTP server address, FTP account’s username and its password. In the next step, we will call this function to connect with FTP server.
2. List files from FTP directory
The next step is to list all files from FTP directory. Create the following function in your FTP class.
public function fetch_files()
{
$this->do_connect();
$path = "/directory-name";
// Get file listing
$file_list = ftp_nlist($this->conn_id, $path);
if ($file_list === false)
{
echo json_encode([
"status" => "error",
"message" => "Error retrieving file list."
]);
exit();
}
$files = [];
foreach ($file_list as $file)
{
$obj = [
"file" => $file,
"size" => ftp_size($this->conn_id, $file)
];
if ($obj["file"] != "." && $obj["file"] != "..")
{
array_push($files, $obj);
}
}
// Close the connection
ftp_close($this->conn_id);
echo json_encode([
"status" => "success",
"message" => "Data has been fetched.",
"files" => $files
]);
exit();
}
This function will first connect with the FTP server.
Then it will fetch all the files from $path variable.
If the directory does not exists or if it does not have read permission, then it will return an error.
All files from that directory will be put in an array along with the size of the file in bytes.
If it is a directory, then it’s size will be -1.
Finally, it returns the array with the response.
3. Fetch file content
Reading the content of FTP file is necessary because in order to edit the file, we need to first view the file. Following function will fetch the content of file and return it in response.
public function fetch_content()
{
$this->do_connect();
$file = "/directory-name/file-name.php";
// Local path for downloading the file
$local_file = tempnam(sys_get_temp_dir(), 'ftp_download');
// Download the file from FTP server to local file
if (!ftp_get($this->conn_id, $local_file, $file, FTP_BINARY))
{
echo json_encode([
"status" => "error",
"message" => "Failed to read '" . $file . "'"
]);
exit();
}
// Read contents of the local file
$file_content = file_get_contents($local_file);
// Display or process the file content as needed
if ($file_content === false)
{
echo json_encode([
"status" => "error",
"message" => "Failed to read file content."
]);
exit();
}
// Clean up: Delete the temporary local file
unlink($local_file);
echo json_encode([
"status" => "success",
"message" => "Data has been fetched.",
"content" => $file_content
]);
exit();
}
It will first download the file in a temporary directory to your server.
If the file does not exists, then it will return an error.
It will return an error if it fails to read the FTP file.
Usually it is because if the $path variable is a directory or an image or document file.
After the file’s content is fetched, we will remove the temporary file from our server.
4. Edit FTP file
After the file’s content is successfully fetched, the next step is to update the file. You are working in FTP, editing the code is what you will be doing most of the time.
Updating the content of file requires 2 steps:
Saving the file in temporary folder.
Uploading the temporary file on FTP server.
public function update_content()
{
$this->do_connect();
$file = "/directory-name/file-name.php";
$content = "console.log(\"Hello world\")";
// Local path for downloading the file
$local_file = tempnam(sys_get_temp_dir(), 'ftp_download');
// Write the new content to a local temporary file
file_put_contents($local_file, $content);
if (!ftp_put($this->conn_id, $remote_file, $local_file, FTP_ASCII))
{
echo json_encode([
"status" => "error",
"message" => "There was a problem updating '" . $remote_file . "'"
]);
exit();
}
unlink($local_file);
// Close the FTP connection
ftp_close($this->conn_id);
echo json_encode([
"status" => "success",
"message" => "File has been updated."
]);
exit();
}
5. Create a new file
Creating a new file in FTP in PHP is as simple as updating the file. We just need to set the content of file as empty string. So we will be uploading an empty file to FTP server.
public function create_file()
{
$this->do_connect();
$path = "/directory-name";
$name = "file-name.php";
// Local file content to be uploaded
$file_content = "";
// Local path for downloading the file
$local_file = tempnam(sys_get_temp_dir(), 'ftp_download');
// Write the content to a temporary local file
file_put_contents($local_file, $file_content);
// Remote file path where the file will be created
$remote_file = $path . "/" . $name; // Replace with the desired remote file path
// Upload the local file to the FTP server
if (!ftp_put($this->conn_id, $remote_file, $local_file, FTP_ASCII))
{
echo json_encode([
"status" => "error",
"message" => "There was a problem while creating '" . $name . "'"
]);
exit();
}
unlink($local_file);
// Close the FTP connection
ftp_close($this->conn_id);
echo json_encode([
"status" => "success",
"message" => "Successfully created '" . $name . "'"
]);
exit();
}
Create a temporary empty file on local directory.
Upload it to FTP.
Remove the file from local directory.
6. Create a new folder
Creating a folder is must easier than creating a file on FTP server.
public function create_folder()
{
$this->do_connect();
$path = "/directory-name";
$name = "folder-name";
$folder = $path . "/" . $name;
if (!ftp_mkdir($this->conn_id, $folder))
{
echo json_encode([
"status" => "error",
"message" => "There was a problem while creating '" . $name . "'"
]);
exit();
}
echo json_encode([
"status" => "success",
"message" => "Successfully created '" . $name . "'"
]);
exit();
}
Note: It will return an error if the directory already exists.
7. Upload files
To upload the file from local computer to FTP server, you need to first save it in your local server. Then upload the file to FTP server. After it is successfully uploaded, you can remove the file from local server.
public function upload()
{
$this->do_connect();
$path = "/directory-name";
$file_name = basename($_FILES["file"]["name"]);
$target_file = "uploads/" . $file_name;
if (!move_uploaded_file($_FILES["file"]["tmp_name"], $target_file))
{
echo json_encode([
"status" => "error",
"message" => "The file " . htmlspecialchars(basename( $_FILES["file"]["name"])) . " has been uploaded."
]);
exit();
}
if (!ftp_put($this->conn_id, $file_name, $target_file, FTP_ASCII))
{
echo json_encode([
"status" => "error",
"message" => "There was a problem updating '" . $file_name . "'"
]);
exit();
}
// Close the FTP connection
ftp_close($this->conn_id);
echo json_encode([
"status" => "success",
"message" => "File(s) has been uploaded."
]);
exit();
}
If you are working in Laravel, your upload function should be like this:
public function upload()
{
$this->do_connect();
$path = "/directory-name";
$files = request()->file("files");
foreach ($files as $file)
{
$remote_file = $file->getClientOriginalName();
$file_path = "ftp/" . $file->getClientOriginalName();
$file->storeAs("/private", $file_path);
if (!ftp_put($this->conn_id, $remote_file, storage_path("app/private/" . $file_path), FTP_ASCII))
{
return response()->json([
"status" => "error",
"message" => "There was a problem updating '" . $remote_file . "'"
]);
}
Storage::delete("private/" . $file_path);
}
// Close the FTP connection
ftp_close($this->conn_id);
return response()->json([
"status" => "success",
"message" => "File(s) has been uploaded."
]);
}
8. Download files
Downloading the file to local computer requires 2 steps.
First is to download the file on local server from FTP server.
Then download it to local computer from local server.
Download file from FTP to local server
Following code will be used to download the file on local server.
public function download()
{
$this->do_connect();
$path = "/directory-name";
$file = "file-name.php";
// Local path for downloading the file
$local_file = tempnam(sys_get_temp_dir(), 'ftp_download');
$remote_file = $path . "/" . $file;
// Download the file from FTP server to local file
if (!ftp_get($this->conn_id, $local_file, $remote_file, FTP_BINARY))
{
echo json_encode([
"status" => "error",
"message" => "Failed to download '" . $remote_file . "'"
]);
exit();
}
// Create a unique download URL for the file
$download_url = url('download.php?file=' . urlencode($local_file) . '&name=' . urlencode($file));
// Close the FTP connection
ftp_close($this->conn_id);
echo json_encode([
"status" => "success",
"message" => "File has been downloaded.",
"download_url" => $download_url
]);
exit();
}
It will also return the “download_url” variable. That will be link to file from where you can download the file.
Download from server to local computer
Create a new file named “download.php” in your server and write the following code in it:
if (isset($_GET['file']) && isset($_GET['name']))
{
$temp_file = $_GET['file'];
$file_name = $_GET['name'];
if (file_exists($temp_file))
{
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file_name . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($temp_file));
// Read the file and output it to the browser
readfile($temp_file);
// Delete the temporary file
unlink($temp_file);
exit();
}
echo "File does not exist.";
exit();
}
echo "Invalid request.";
exit();
9. Rename file
Renaming the file on FTP using PHP is very easy. You just have to provide 3 things:
Folder name
Old file name
New file name
public function rename()
{
$this->do_connect();
$path = "/directory-name";
$name = "new-file-name.php";
$file = "old-file-name.php";
// File to be renamed on the FTP server
$remote_file = $path . "/" . $file;
$remote_new_file = $path . "/" . $name;
// Try to rename the file or folder
if (!ftp_rename($this->conn_id, $remote_file, $remote_new_file))
{
echo json_encode([
"status" => "error",
"message" => "There was a problem renaming " . $file . " to " . $name
]);
exit();
}
echo json_encode([
"status" => "success",
"message" => "Successfully renamed " . $file . " to " . $name
]);
exit();
}
10. Delete file
Deleting a file from FTP in PHP is very simply. You just need to enter the full path of the file and call the PHP built-in ftp_delete function. Pass the FTP connection ID and file path as arguments.
public function delete_file()
{
$this->do_connect();
$path = "/directory-name/file-name.php";
// Delete the file on the FTP server
if (!ftp_delete($this->conn_id, $path))
{
echo json_encode([
"status" => "error",
"message" => "There was a problem while deleting " . $path
]);
exit();
}
echo json_encode([
"status" => "success",
"message" => "Successfully deleted " . $path
]);
exit();
}
11. Delete folder
Deleting a folder is NOT as simple as deleting a single file. There are 2 steps involved in deleting a folder from FTP in PHP.
Recursively delete all files and folders inside that folder.
Delete the folder itself.
So first we will create a function that will initialize the call to recursive function.
public function delete_folder()
{
// Set maximum execution time to unlimited (0 means no limit)
set_time_limit(0);
$path = "/directory-path/folder-name";
$this->do_connect();
$this->ftp_delete_dir($path);
echo json_encode([
"status" => "success",
"message" => "Folder has been deleted."
]);
exit();
}
Our recursive function ftp_delete_dir will look like this:
// Function to recursively delete a directory
private function ftp_delete_dir($path)
{
// Get the list of files in the directory
$files = ftp_nlist($this->conn_id, $path);
// Loop through each file
foreach ($files as $file)
{
$file = basename($file);
if ($file == '.' || $file == '..')
{
continue;
}
$file_path = "$path/$file";
// If it's a directory, delete recursively
if (@ftp_chdir($this->conn_id, $file_path))
{
ftp_chdir($this->conn_id, '..');
ftpDelete($this->conn_id, $file_path);
}
else
{
// If it's a file, delete it
ftp_delete($this->conn_id, $file_path);
}
}
// Finally, remove the directory itself
ftp_rmdir($this->conn_id, $path);
}
It does the following things:
Loops through all the files inside that folder.
Skip the “.” and “..” folders (they are just pointing towards current and parent directory respectively).
If the file is a directory, start the recursion.
Else delete the file.
Finally at line #33, we are deleting the current directory itself.
So these are all the features we have in FTP manager I created in PHP and MySQL using Laravel framework. If you have any quetions regarding FTP or if you are having any problem, feel free to contact me.
If you are working in Firebase, then you might have encountered an issue with child_added event or onChildAdded method. It is called multiple times on page load. However, it should have been called only when a new child is added. As per Firebase documentation, this is the expected behavior. It first returns all the existing childs and then listen for new added children. But there might be a scenario where you want to perform some action only on new child, not on existing children.
So I have a Firebase database and I have a users array in it.
Firebase database users
Step 1
The way I got around this problem, is by first I am looping through all the records in Firebase.
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-app.js";
import { getDatabase, ref, get, onChildAdded } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-database.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
const usersRef = ref(database, "users")
// [step 2]
get(usersRef).then(function (snapshot) {
if (snapshot.exists()) {
snapshot.forEach(function (childSnapshot) {
// [step 3]
})
}
})
</script>
Note: Make sure to use your own Firebase configurations. If you do not know how to setup Firebase configurations, you can follow our guide.
Step 2
After that, we will create a variable that will count the length of users array. Write the following line in place of // [step 2].
let count = 0
This will initialize the variable “count”.
Step 3
Then increment that variable’s value by 1. Following code goes in place of // [step 3].
count++
if (snapshot.size == count) {
// [step 4]
}
This will also checks when all the element of array has been looped.
Step 4
Initialize another variable that will tell if all the elements has been fetched.
let hasInitializedFirebase = false
Then we will set its value to true at // [step 4].
We are adding a delay of 1 second to prevent the onChildAdded event to be called immidiately.
Step 5
Last step is to call the onChildAdded event and check if the variable hasInitializedFirebase is true.
onChildAdded(usersRef, async function (data) {
if (hasInitializedFirebase) {
console.log(data)
}
})
If you reload the page now, you will not see the onChildAdded logs, but as soon as you insert a new element in array, you will see that the console.log(data) has been called.
Complete code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test</title>
</head>
<body>
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-app.js";
import { getDatabase, ref, get, set, push, onChildAdded, onChildChanged } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-database.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
const usersRef = ref(database, "users")
let count = 0
let hasInitializedFirebase = false
get(usersRef).then(function (snapshot) {
if (snapshot.exists()) {
snapshot.forEach(function (childSnapshot) {
count++
if (snapshot.size == count) {
setTimeout(function () {
hasInitializedFirebase = true;
}, 1000)
}
})
} else {
setTimeout(function () {
hasInitializedFirebase = true;
}, 1000)
}
})
onChildAdded(usersRef, async function (data) {
if (hasInitializedFirebase) {
console.log(data)
}
})
</script>
</body>
</html>
That’s how you can prevent onChildAdded event to be called multiples times in Firebase. If you face any problem in this, feel free to contact me from chat widget on bottom right.
Getting file extension from file name or path can be done in Javascript and PHP. I will show you the steps to get the file extension and you can apply them in any language you want.
Following code will get the file extension from file name or file path in Javascript:
Suppose you are creating a tab layout where there are multiple tabs and each tab has its own content. You click on the tab button and its content is displayed.
But when you refresh the page, it starts from the first tab again. How can you make so that when you refresh the page, it keeps the last active tab as “active” ?
Bootstrap Tabs
Following code will display a tab layout with 3 tabs in Bootstrap 5:
Right now it makes the “Home” tab active. When you click on other tabs, you will see their content. But once you refresh the page, it will again make the home tab active regardless of which tab you clicked last time.
Updating URL
Next step is to set the value of current tab in the URL when user changes the tab. So on each tab button, we will add an onclick listener that will call a function to update the URL in the browser.
If you want to learn more about this in detail, you can read this article.
If you change the tabs now, you will see that the “tab” query will be appended in the URL and its value will be the tab clicked. But if you refresh the page now, the tab will not be highlighted yet. This is because we are setting the “tab” query in URL but not reading it.
Highlight current tab as active
Last step is to get the current tab from the URL and highlight it.
<?php
$tab = $_GET["tab"] ?? "home";
?>
This is get the “tab” query from URL parameter. If it does not exists in the URL, then the default value of $tab variable will be “home”.
Following is the updated code that will highlight the tab button and also will show its content.
Following is the complete code that displays 3 tabs along with their contents. On change, will set the query parameter in the URL. After refresh will highlight the tab last selected.
If you are using the DataTable Javascript library and are having trouble searching in all fields of the dataset except for the only one visible, then I will show you, how you can search in all fields of the DataTable.
By default, DataTable searches in all fields only on those fields that are visible on the table. Let’s say you have a dataset containing “name”, “designation”, and “country” fields. But you are displaying only “name”, and “designation” on the table.
In this article, we will discuss how you can hide or show any UI if the value of a variable is true in React JS. Following this tutorial, you will also learn how to use the if condition in React JS. You just need to do 3 things:
By default, you will not see the second button because the default value is false. Try changing the value of the variable from false to true, you will start seeing the UI.
A Job Portal website is created in PHP and MySQL using MVC architecture. MVC stands for Model-View-Controller and this architectural design is used by many websites for scalability.
✅ Compatible with almost every shared/dedicated/VPS hosting.
✅ Free support.
New features:
✅ Optimized sending bulk emails.
Files included:
.php
.css
.js
Tech stack:
PHP +7.0
MySQL +5.0
Bootstrap 4
Vue JS 3
Recruiter can post a job
Recruiter posted jobs
Change status of applicant
Edit/delete job
A recruiter can edit or delete any of his posted jobs at any time. This helps if the recruiter needs to change the requirements for a job or delete if the vacancy is already been filled.
Jobs Listing
Users will get a listing of all the jobs posted by recruiters.
Job Detail
They can view the job details by clicking the job title.
Filter Jobs
On the jobs listing page, users can filter jobs by the type of job they want, like developer, designer, etc. By the location to see if the job is in their city or if they can relocate to that city. Or by the nature of the job i.e. is the job part-time, full-time, or remote. Users can also search the jobs in their salary range. This way they can find jobs that pay them according to their needs.
Real-time updates on new jobs
Users will get real-time updates whenever a new job is posted by the recruiter. They do not have to refresh the page to check if there is any new job. To develop this feature, I have used sockets. You need to install Node JS in your system or server to make this feature work. Even if you do not have Node JS installed, all other features will work except for real-time job updates.
Email notifications of new jobs
Users can turn on notifications from recruiters. Whenever that recruiter posts a new job, all the users who have turned on their notifications will receive an email.
Admin can see all the stats
The admin of the website can see the total number of users registered. The total number of jobs that have been posted by recruiters. And the total number of applications that have been submitted for those jobs. The admin can see all this information on his dashboard.
Manage users
Admin will have the option to add new users to the website. While adding, he/she can select if the user be an applicant or a recruiter. Admin can also manage existing users. Admin can edit the user and can also delete the user if required. Admin can change the password of the user as well. This is helpful if the user is finding it difficult to receive the password reset email. Or if you want to prevent the user from logging in.
Deployment
This Job Portal website can be deployed on any server that supports PHP and MySQL.
In this tutorial, we will teach you, how you can convert UTC time to your local timezone in Node JS.
Following code will first get the current datetime in UTC, then convert it to user local timezone.
Note: You do not need to provide the timeZone from client side. Node JS will automatically detect the timeZone from incoming request and convert it accordingly.
let date = new Date()
date = new Date(date + " UTC")
date = date.toUTCString()
result.send(date + "")
If you want to return the datetime in specific format, you can do it like this:
// Options for date and time formattingconst options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true}const date = (newDate()).toLocaleString("en-US", options)
This will return the date and time in format: “Tuesday, 2 July, 2024 at 05:11:05 pm”.