Posted on Leave a comment

Sort a List, String, Tuple in Python (sort, sorted)

5/5 – (1 vote)

Basics of Sorting in Python

In Python, sorting data structures like lists, strings, and tuples can be achieved using built-in functions like sort() and sorted(). These functions enable you to arrange the data in ascending or descending order. This section will provide an overview of how to use these functions.

The sorted() function is primarily used when you want to create a new sorted list from an iterable, without modifying the original data. This function can be used with a variety of data types, such as lists, strings, and tuples.

Here’s an example of sorting a list of integers:

numbers = [5, 8, 2, 3, 1]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 3, 5, 8]

To sort a string or tuple, you can simply pass it to the sorted() function as well:

text = "python"
sorted_text = sorted(text)
print(sorted_text) # Output: ['h', 'n', 'o', 'p', 't', 'y']

For descending order sorting, use the reverse=True argument with the sorted() function:

numbers = [5, 8, 2, 3, 1]
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc) # Output: [8, 5, 3, 2, 1]

On the other hand, the sort() method is used when you want to modify the original list in-place. One key point to note is that the sort() method can only be called on lists and not on strings or tuples.

To sort a list using the sort() method, simply call this method on the list object:

numbers = [5, 8, 2, 3, 1]
numbers.sort()
print(numbers) # Output: [1, 2, 3, 5, 8]

For descending order sorting using the sort() method, pass the reverse=True argument:

numbers = [5, 8, 2, 3, 1]
numbers.sort(reverse=True)
print(numbers) # Output: [8, 5, 3, 2, 1]

Using the sorted() function and the sort() method, you can easily sort various data structures in Python, such as lists, strings, and tuples, in ascending or descending order.

💡 Recommended: Python List sort() – The Ultimate Guide

Sorting Lists

In Python, sorting a list is a common operation that can be performed using either the sort() method or the sorted() function. Both these approaches can sort a list in ascending or descending order.

Using .sort() Method

The sort() method is a built-in method of the list object in Python. It sorts the elements of the list in-place, meaning it modifies the original list without creating a new one. By default, the sort() method sorts the list in ascending order.

YouTube Video

Here’s an example of how to use the sort() method to sort a list of numbers:

numbers = [5, 2, 8, 1, 4]
numbers.sort()
print(numbers) # Output: [1, 2, 4, 5, 8]

To sort the list in descending order, you can pass the reverse=True argument to the sort() method:

numbers = [5, 2, 8, 1, 4]
numbers.sort(reverse=True)
print(numbers) # Output: [8, 5, 4, 2, 1]

Sorting Lists with sorted() Function

The sorted() function is another way of sorting a list in Python. Unlike the sort() method, the sorted() function returns a new sorted list without modifying the original one.

Here’s an example showing how to use the sorted() function:

numbers = [5, 2, 8, 1, 4]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 4, 5, 8]

Similar to the sort() method, you can sort a list in descending order using the reverse=True argument:

numbers = [5, 2, 8, 1, 4]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers) # Output: [8, 5, 4, 2, 1]

Both the sort() method and sorted() function allow for sorting lists as per specified sorting criteria. Use them as appropriate depending on whether you want to modify the original list or get a new sorted list.

Check out my video on the sorted() function: 👇

YouTube Video

💡 Recommended: Python sorted() Function

Sorting Tuples

Tuples are immutable data structures in Python, similar to lists, but they are enclosed within parentheses and cannot be modified once created. Sorting tuples can be achieved using the built-in sorted() function.

Ascending and Descending Order

To sort a tuple or a list of tuples in ascending order, simply pass the tuple to the sorted() function.

Here’s an example:

my_tuple = (3, 1, 4, 5, 2)
sorted_tuple = sorted(my_tuple)
print(sorted_tuple) # Output: [1, 2, 3, 4, 5]

For descending order, use the optional reverse argument in the sorted() function. Setting it to True will sort the elements in descending order:

my_tuple = (3, 1, 4, 5, 2)
sorted_tuple = sorted(my_tuple, reverse=True)
print(sorted_tuple) # Output: [5, 4, 3, 2, 1]

Sorting Nested Tuples

When sorting a list of tuples, Python sorts them by the first elements in the tuples, then the second elements, and so on. To effectively sort nested tuples, you can provide a custom sorting key using the key argument in the sorted() function.

Here’s an example of sorting a list of tuples in ascending order by the second element in each tuple:

my_list = [(1, 4), (3, 1), (2, 5)]
sorted_list = sorted(my_list, key=lambda x: x[1])
print(sorted_list) # Output: [(3, 1), (1, 4), (2, 5)]

Alternatively, to sort in descending order, simply set the reverse argument to True:

my_list = [(1, 4), (3, 1), (2, 5)]
sorted_list = sorted(my_list, key=lambda x: x[1], reverse=True)
print(sorted_list) # Output: [(2, 5), (1, 4), (3, 1)]

As shown, you can manipulate the sorted() function through its arguments to sort tuples and lists of tuples with ease. Remember, tuples are immutable, and the sorted() function returns a new sorted list rather than modifying the original tuple.

Sorting Strings

In Python, sorting strings can be done using the sorted() function. This function is versatile and can be used to sort strings (str) in ascending (alphabetical) or descending (reverse alphabetical) order.

In this section, we’ll explore sorting individual characters in a string and sorting a list of words alphabetically.

Sorting Characters

To sort the characters of a string, you can pass the string to the sorted() function, which will return a list of characters in alphabetical order. Here’s an example:

text = "python"
sorted_chars = sorted(text)
print(sorted_chars)

Output:

['h', 'n', 'o', 'p', 't', 'y']

If you want to obtain the sorted string instead of the list of characters, you can use the join() function to concatenate them:

sorted_string = ''.join(sorted_chars)
print(sorted_string)

Output:

hnopty

For sorting the characters in descending order, set the optional reverse parameter to True:

sorted_chars_desc = sorted(text, reverse=True)
print(sorted_chars_desc)

Output:

['y', 't', 'p', 'o', 'n', 'h']

Sorting Words Alphabetically

When you have a list of words and want to sort them alphabetically, the sorted() function can be applied directly to the list:

words = ['apple', 'banana', 'kiwi', 'orange']
sorted_words = sorted(words)
print(sorted_words)

Output:

['apple', 'banana', 'kiwi', 'orange']

To sort the words in reverse alphabetical order, use the reverse parameter again:

sorted_words_desc = sorted(words, reverse=True)
print(sorted_words_desc)

Output:

['orange', 'kiwi', 'banana', 'apple']

Using Key Parameter

👉 Image Source: Finxter Blog

The key parameter in Python’s sort() and sorted() functions allows you to customize the sorting process by specifying a callable to be applied to each element of the list or iterable.

Sorting with Lambda

Using lambda functions as the key argument is a concise way to sort complex data structures. For example, if you have a list of tuples representing names and ages, you can sort by age using a lambda function:

names_ages = [('Alice', 30), ('Bob', 25), ('Charlie', 35)]
sorted_names_ages = sorted(names_ages, key=lambda x: x[1])
print(sorted_names_ages)

Output:

[('Bob', 25), ('Alice', 30), ('Charlie', 35)]

Using itemgetter from operator Module

An alternative to using lambda functions is the itemgetter() function from the operator module. The itemgetter() function can be used as the key parameter to sort by a specific index in complex data structures:

from operator import itemgetter names_ages = [('Alice', 30), ('Bob', 25), ('Charlie', 35)]
sorted_names_ages = sorted(names_ages, key=itemgetter(1))
print(sorted_names_ages)

Output:

[('Bob', 25), ('Alice', 30), ('Charlie', 35)]

Sorting with Custom Functions

You can also create custom functions to be used as the key parameter. For example, to sort strings based on the number of vowels:

def count_vowels(s): return sum(s.count(vowel) for vowel in 'aeiouAEIOU') words = ['apple', 'banana', 'cherry']
sorted_words = sorted(words, key=count_vowels)
print(sorted_words)

Output:

['apple', 'cherry', 'banana']

Sorting Based on Absolute Value

To sort a list of integers based on their absolute values, you can use the built-in abs() function as the key parameter:

numbers = [5, -3, 1, -8, -7]
sorted_numbers = sorted(numbers, key=abs)
print(sorted_numbers)

Output:

[1, -3, 5, -7, -8]

Sorting with cmp_to_key from functools

In some cases, you might need to sort based on a custom comparison function. The cmp_to_key() function from the functools module can be used to achieve this. For instance, you could create a custom comparison function to sort strings based on their lengths:

from functools import cmp_to_key def custom_cmp(a, b): return len(a) - len(b) words = ['cat', 'bird', 'fish', 'ant']
sorted_words = sorted(words, key=cmp_to_key(custom_cmp))
print(sorted_words)

Output:

['cat', 'ant', 'bird', 'fish']

Sorting with Reverse Parameter

In Python, you can easily sort lists, strings, and tuples using the built-in functions sort() and sorted(). One notable feature of these functions is the reverse parameter, which allows you to control the sorting order – either in ascending or descending order.

By default, the sort() and sorted() functions will sort the elements in ascending order. To sort them in descending order, you simply need to set the reverse parameter to True. Let’s explore this with some examples.

Suppose you have a list of numbers and you want to sort it in descending order. You can use the sort() method for lists:

numbers = [4, 1, 7, 3, 9]
numbers.sort(reverse=True) # sorts the list in place in descending order
print(numbers) # Output: [9, 7, 4, 3, 1]

If you have a string or a tuple and want to sort in descending order, use the sorted() function:

text = "abracadabra"
sorted_text = sorted(text, reverse=True)
print(sorted_text) # Output: ['r', 'r', 'd', 'c', 'b', 'b', 'a', 'a', 'a', 'a', 'a'] values = (4, 1, 7, 3, 9)
sorted_values = sorted(values, reverse=True)
print(sorted_values) # Output: [9, 7, 4, 3, 1]

Keep in mind that the sort() method works only on lists, while the sorted() function works on any iterable, returning a new sorted list without modifying the original iterable.

When it comes to sorting with custom rules, such as sorting a list of tuples based on a specific element, you can use the key parameter in combination with the reverse parameter. For example, to sort a list of tuples by the second element in descending order:

data = [("apple", 5), ("banana", 3), ("orange", 7), ("grape", 2)]
sorted_data = sorted(data, key=lambda tup: tup[1], reverse=True)
print(sorted_data) # Output: [('orange', 7), ('apple', 5), ('banana', 3), ('grape', 2)]

So the reverse parameter in Python’s sorting functions provides you with the flexibility to sort data in either ascending or descending order. By combining it with other parameters such as key, you can achieve powerful and customized sorting for a variety of data structures.

Sorting in Locale-Specific Order

Sorting lists, strings, and tuples in Python is a common task, and it often requires locale-awareness to account for language-specific rules. You can sort a list, string or tuple using the built-in sorted() function or the sort() method of a list. But to sort it in a locale-specific order, you must take into account the locale’s sorting rules and character encoding.

We can achieve locale-specific sorting using the locale module in Python. First, you need to import the locale library and set the locale using the setlocale() function, which takes two arguments, the category and the locale name.

import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # Set the locale to English (US)

Next, use the locale.strxfrm() function as the key for the sorted() function or the sort() method. The strxfrm() function transforms a string into a form suitable for locale-aware comparisons, allowing the sorting function to order the strings according to the locale’s rules.

strings_list = ['apple', 'banana', 'Zebra', 'éclair']
sorted_strings = sorted(strings_list, key=locale.strxfrm)

The sorted_strings list will now be sorted according to the English (US) locale, with case-insensitive and accent-aware ordering.

Keep in mind that it’s essential to set the correct locale before sorting, as different locales may have different sorting rules. For example, the German locale would handle umlauts differently from English, so setting the locale to de_DE.UTF-8 would produce a different sorting order.

Sorting Sets

In Python, sets are unordered collections of unique elements. To sort a set, we must first convert it to a list or tuple, since the sorted() function does not work directly on sets. The sorted() function returns a new sorted list from the specified iterable, which can be a list, tuple, or set.

import locale
strings_list = ['apple', 'banana', 'Zebra', 'éclair']
sorted_strings = sorted(strings_list, key=locale.strxfrm)
print(sorted_strings)
# ['Zebra', 'apple', 'banana', 'éclair']

In this example, we begin with a set named sample_set containing four integers. We then use the sorted() function to obtain a sorted list named sorted_list_from_set. The output will be:

[1, 2, 4, 9]

The sorted() function can also accept a reverse parameter, which determines whether to sort the output in ascending or descending order. By default, reverse is set to False, meaning that the output will be sorted in ascending order. To sort the set in descending order, we can set reverse=True.

sorted_list_descending = sorted(sample_set, reverse=True)
print(sorted_list_descending)

This code snippet will output the following:

[9, 4, 2, 1]

It’s essential to note that sorting a set using the sorted() function does not modify the original set. Instead, it returns a new sorted list, leaving the original set unaltered.

Sorting by Group and Nested Data Structures

Sorting nested data structures in Python can be achieved using the built-in sorted() function or the .sort() method. You can sort a list of lists or tuples based on the value of a particular element in the inner item, making it useful for organizing data in groups.

To sort nested data, you can use a key argument along with a lambda function or the itemgetter() method from the operator module. This allows you to specify the criteria based on which the list will be sorted.

For instance, suppose you have a list of tuples representing student records, where each tuple contains the student’s name and score:

students = [("Alice", 85), ("Bob", 78), ("Charlie", 91), ("Diana", 92)]

To sort the list by the students’ scores, you can use the sorted() function with a lambda function as the key:

sorted_students = sorted(students, key=lambda student: student[1])

This will produce the following sorted list:

[("Bob", 78), ("Alice", 85), ("Charlie", 91), ("Diana", 92)]

Alternatively, you can use the itemgetter() method:

from operator import itemgetter sorted_students = sorted(students, key=itemgetter(1))

This will produce the same result as using the lambda function.

When sorting lists containing nested data structures, consider the following tips:

  • Use the lambda function or itemgetter() for specifying the sorting criteria.
  • Remember that sorted() creates a new sorted list, while the .sort() method modifies the original list in-place.
  • You can add the reverse=True argument if you want to sort the list in descending order.

Handling Sorting Errors

When working with sorting functions in Python, you might encounter some common errors such as TypeError. In this section, we’ll discuss how to handle such errors and provide solutions to avoid them while sorting lists, strings, and tuples using the sort() and sorted() functions.

TypeError can occur when you’re trying to sort a list that contains elements of different data types. For example, when sorting an unordered list that contains both integers and strings, Python would raise a TypeError: '<' not supported between instances of 'str' and 'int' as it cannot compare the two different data types.

Consider this example:

mixed_list = [3, 'apple', 1, 'banana']
mixed_list.sort()
# Raises: TypeError: '<' not supported between instances of 'str' and 'int'

To handle the TypeError in this case, you can use error handling techniques such as a try-except block. Alternatively, you could also preprocess the list to ensure all elements have a compatible data type before sorting. Here’s an example using a try-except block:

mixed_list = [3, 'apple', 1, 'banana']
try: mixed_list.sort()
except TypeError: print("Sorting error occurred due to incompatible data types")

Another approach is to sort the list using a custom sorting key in the sorted() function that can handle mixed data types. For instance, you can convert all the elements to strings before comparison:

mixed_list = [3, 'apple', 1, 'banana']
sorted_list = sorted(mixed_list, key=str)
print(sorted_list) # Output: [1, 3, 'apple', 'banana']

With these techniques, you can efficiently handle sorting errors that arise due to different data types within a list, string, or tuple when using the sort() and sorted() functions in Python.

Sorting Algorithm Stability

Stability in sorting algorithms refers to the preservation of the relative order of items with equal keys. In other words, when two elements have the same key, their original order in the list should be maintained after sorting. Python offers several sorting techniques, with the most common being sort() for lists and sorted() for strings, lists, and tuples.

Python’s sorting algorithms are stable, which means that equal keys will have their initial order preserved in the sorted output. For example, consider a list of tuples containing student scores and their names:

students = [(90, "Alice"), (80, "Bob"), (90, "Carla"), (85, "Diana")]

Sorted by scores, the list should maintain the order of students with equal scores as in the original list:

sorted_students = sorted(students)
# Output: [(80, 'Bob'), (85, 'Diana'), (90, 'Alice'), (90, 'Carla')]

Notice that Alice and Carla both have a score of 90 but since Alice appeared earlier in the original list, she comes before Carla in the sorted list as well.

To take full advantage of stability in sorting, the key parameter can be used with both sort() and sorted(). The key parameter allows you to specify a custom function or callable to be applied to each element for comparison. For instance, when sorting a list of strings, you can provide a custom function to perform a case-insensitive sort:

words = ["This", "is", "a", "test", "string", "from", "Andrew"]
sorted_words = sorted(words, key=str.lower)
# Output: ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

Frequently Asked Questions

How to sort a list of tuples in descending order in Python?

To sort a list of tuples in descending order, you can use the sorted() function with the reverse=True parameter. For example, for a list of tuples tuples_list, you can sort them in descending order like this:

sorted_tuples = sorted(tuples_list, reverse=True)

What is the best way to sort a string alphabetically in Python?

The best way to sort a string alphabetically in Python is to use the sorted() function, which returns a sorted list of characters. You can then join them using the join() method like this:

string = "hello"
sorted_string = "".join(sorted(string))

What are the differences between sort() and sorted() in Python?

sort() is a method available for lists, and it sorts the list in-place, meaning it modifies the original list. sorted() is a built-in function that works with any iterable, returns a new sorted list of elements, and doesn’t modify the original iterable.

# Using sort()
numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers) # [1, 2, 3, 4] # Using sorted()
numbers = (3, 1, 4, 2)
sorted_numbers = sorted(numbers)
print(sorted_numbers) # [1, 2, 3, 4]

How can you sort a tuple in descending order in Python?

To sort a tuple in descending order, you can use the sorted() function with the reverse=True parameter, like this:

tuple_numbers = (3, 1, 4, 2)
sorted_tuple = sorted(tuple_numbers, reverse=True)

Keep in mind that this will create a new list. If you want to create a new tuple instead, you can convert the sorted list back to a tuple like this:

sorted_tuple = tuple(sorted_tuple)

How do you sort a string in Python without using the sort function?

You can sort a string without using the sort() function by converting the string to a list of characters, using a list comprehension to sort the characters, and then using the join() method to create the sorted string:

string = "hello"
sorted_list = [char for char in sorted(string)]
sorted_string = "".join(sorted_list)

What is the method to sort a list of strings with numbers in Python?

If you have a list of strings containing numbers and want to sort them based on the numeric value, you can use the sorted() function with a custom key parameter. For example, to sort a list of strings like ["5", "2", "10", "1"], you can do:

strings_with_numbers = ["5", "2", "10", "1"]
sorted_strings = sorted(strings_with_numbers, key=int)

This will sort the list based on the integer values of the strings: ["1", "2", "5", "10"].

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!

The post Sort a List, String, Tuple in Python (sort, sorted) appeared first on Be on the Right Side of Change.

Posted on Leave a comment

Upload and Display Image in PHP

by Vincy. Last modified on July 5th, 2023.

PHP upload is a single-line, built-in function invocation. Any user inputs, especially files, can not be processed without proper filtering. Why? Because people may upload harmful files to the server.

After file upload, the status has to be shown in the UI as an acknowledgment. Otherwise, showing the uploaded image’s preview is the best way of acknowledging the end user.

View Demo
Earlier, we saw how to show the preview of images extracted from a remote URL.

This article will provide a short and easy example in PHP to upload and display images.

upload and display image php

Steps to upload and display the image preview on the browser

  1. Show an image upload option in an HTML form.
  2. Read file data from the form and set the upload target.
  3. Validate the file type size before uploading to the server.
  4. Call the PHP upload function to save the file to the target.
  5. Display the uploaded image on the browser

1. Show an image upload option in an HTML form

This code is to show an HTML form with a file input to the user. This form is with enctype="multipart/form-data" attribute. This attribute is for uploading the file binary to be accessible on the PHP side.

<form action="" method="post" enctype="multipart/form-data"> <div class="row"> <input type="file" name="image" required> <input type="submit" name="submit" value="Upload"> </div>
</form>

Read file data from the form and set the upload target

This section shows a primary PHP condition to check if the form is posted and the file binary is not empty.

Once these conditions return true, further steps will be taken for execution.

Once the image is posted, it sets the target directory path to upload. The variable $uploadOK is a custom flag to allow the PHP file upload.

If the validation returns false, this $uploadOK variable will be turned to 0 and stop uploading.

<?php
if (isset($_POST["submit"])) { // Check image using getimagesize function and get size // if a valid number is got then uploaded file is an image if (isset($_FILES["image"])) { // directory name to store the uploaded image files // this should have sufficient read/write/execute permissions // if not already exists, please create it in the root of the // project folder $targetDir = "uploads/"; $targetFile = $targetDir . basename($_FILES["image"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION)); // Validation here }
}
?>

Validate the file type size before uploading to the server

This example applies three types of validation criteria on the server side.

  1. Check if the uploaded file is an image.
  2. Check if the image has the accepted size limit (0.5 MB).
  3. Check if the image has the allowed extension (jpeg and png).
<?php
// Check image using getimagesize function and get size // if a valid number is got then uploaded file is an image if (isset($_FILES["image"])) { // directory name to store the uploaded image files // this should have sufficient read/write/execute permissions // if not already exists, please create it in the root of the // project folder $targetDir = "uploads/"; $targetFile = $targetDir . basename($_FILES["image"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION)); $check = getimagesize($_FILES["image"]["tmp_name"]); if ($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } // Check if the file already exists in the same path if (file_exists($targetFile)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size and throw error if it is greater than // the predefined value, here it is 500000 if ($_FILES["image"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Check for uploaded file formats and allow only // jpg, png, jpeg and gif // If you want to allow more formats, declare it here if ( $imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; }
?>

4. Call the PHP upload function to save the file to the target

Once the validation is completed, then the PHP move_uploaded_file() the function is called.

It copies the file from the temporary path to the target direct set in step 1.

<?php
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) { echo "Sorry, your file was not uploaded.";
} else { if (move_uploaded_file($_FILES["image"]["tmp_name"], $targetFile)) { echo "The file " . htmlspecialchars(basename($_FILES["image"]["name"])) . " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; }
}
?>

5. Display the uploaded image on the browser.

This section shows the image preview by setting the source path.

Before setting the preview source, this code ensures the upload status is ‘true.’

<h1>Display uploaded Image:</h1>
<?php if (isset($_FILES["image"]) && $uploadOk == 1) : ?> <img src="<?php echo $targetFile; ?>" alt="Uploaded Image">
<?php endif; ?>

Create a directory called “uploads” in the root directory of the downloaded example project. Uploaded images will be stored in this folder.

Note: The “uploads” directory should have sufficient file permissions.
View Demo Download

↑ Back to Top

Posted on Leave a comment

PHP Upload Image to Database with MySql

by Vincy. Last modified on July 2nd, 2023.

Do you want to upload an image to the database? Most application services move the uploaded files to a directory and save their path to the database.

Earlier, we saw code for storing uploaded images to the database using MySQL BLOB fields. BLOB(Binary Large Data Object) is one of the MySql data types. It can have the file binary data. MySQL supports four types of BLOB datatype as follows.
View demo

  1. TINYBLOB
  2. BLOB
  3. MEDIUMBLOB
  4. LONGBLOB

For this example, we created one of the above BLOB fields in a MySQL database to see how to upload an image. Added to that, this code will fetch and BLOB data from the database and display the image to the browser.

Database script

Before running this example, create the required database structure on your server.

CREATE TABLE images ( id INT(11) AUTO_INCREMENT PRIMARY KEY, image LONGBLOB NOT NULL );

php upload image to database output

HTML form with an image upload option

This is a usual file upload form with a file input. This field restricts the file type to choose only the images using the accept attribute.

On submitting this form, the upload.php receives the posted file binary data on the server side.

<!DOCTYPE html>
<html> <head> <title>PHP - Upload image to database - Example</title> <link href="style.css" rel="stylesheet" type="text/css" /> <link href="form.css" rel="stylesheet" type="text/css" />
</head> <body> <div class="phppot-container"> <h1>Upload image to database:</h1> <form action="upload.php" method="post" enctype="multipart/form-data"> <div class="row"> <input type="file" name="image" accept="image/*"> <input type="submit" value="Upload"> </div> </form> <h2>Uploaded Image (Displayed from the database)</h2> </div>
</body> </html>

Insert an image into the database using PHP and MySql

This PHP script gets the chosen file data with the $_FILES array. This array contains the base name, temporary source path, type, and more details.

With these details, it performs the file upload to the database. The steps are as follows,

  1. Validate file array is not empty.
  2. Retrieve the image file content using file_get_contents($_FILES[“image”][“tmp_name”]).
  3. Prepare the insert and bind the image binary data to the query parameters.
  4. Execute insert and get the database record id.
<?php
// MySQL database connection settings
$servername = "localhost";
$username = "root";
$password = "admin123";
$dbname = "phppot_image_upload"; // Make connection
$conn = new mysqli($servername, $username, $password, $dbname); // Check connection and throw error if not available
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);
} // Check if an image file was uploaded
if (isset($_FILES["image"]) && $_FILES["image"]["error"] == 0) { $image = $_FILES['image']['tmp_name']; $imgContent = file_get_contents($image); // Insert image data into database as BLOB $sql = "INSERT INTO images(image) VALUES(?)"; $statement = $conn->prepare($sql); $statement->bind_param('s', $imgContent); $current_id = $statement->execute() or die("<b>Error:</b> Problem on Image Insert<br/>" . mysqli_connect_error()); if ($current_id) { echo "Image uploaded successfully."; } else { echo "Image upload failed, please try again."; }
} else { echo "Please select an image file to upload.";
} // Close the database connection
$conn->close();

Fetch image BLOB from the database and display to UI

This PHP code prepares a SELECT query to fetch the image BLOB. Using the image binary from the BLOB, it creates the data URL. It applies PHP base64 encoding on the image binary content.

This data URL is set as a source of an HTML image element below. This script shows the recently inserted image on the screen. We can also show an image gallery of all the BLOB images from the database.

<?php // Retrieve the uploaded image from the database $servername = "localhost"; $username = "root"; $password = ""; $dbname = "phppot_image_upload"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $result = $conn->query("SELECT image FROM images ORDER BY id DESC LIMIT 1"); if ($result && $result->num_rows > 0) { $row = $result->fetch_assoc(); $imageData = $row['image']; echo '<img src="data:image/jpeg;base64,' . base64_encode($imageData) . '" alt="Uploaded Image" style="max-width: 500px;">'; } else { echo 'No image uploaded yet.'; } $conn->close(); ?>

View demo Download

↑ Back to Top

Posted on Leave a comment

Gauge Chart JS – Speedometer Example

A gauge chart is a scale to measure performance amid the target. Yeah! My attempt at defining ‘Gauge.’ This article uses the ChartJS JavaScript library to create a gauge chat.

The below example creates a speedometer in the form of a gauge change. It achieves this with type=doughnut. The other options, cutout, rotation, and circumference, make the expected gauge chart view.
View Demo

<!DOCTYPE html>
<html> <head> <title>Gauge Chart Example using Chart.js</title> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head> <body> <canvas id="gaugeChart"></canvas> <script> // data for the gauge chart // you can supply your own values here // max is the Gauge's maximum value var data = { value: 200, max: 300, label: "Progress" }; // Chart.js chart's configuration // We are using a Doughnut type chart to // get a Gauge format chart // This is approach is fine and actually flexible // to get beautiful Gauge charts out of it var config = { type: 'doughnut', data: { labels: [data.label], datasets: [{ data: [data.value, data.max - data.value], backgroundColor: ['rgba(54, 162, 235, 0.8)', 'rgba(0, 0, 0, 0.1)'], borderWidth: 0 }] }, options: { responsive: true, maintainAspectRatio: false, cutoutPercentage: 85, rotation: -90, circumference: 180, tooltips: { enabled: false }, legend: { display: false }, animation: { animateRotate: true, animateScale: false }, title: { display: true, text: data.label, fontSize: 16 } } }; // Create the chart var chartCtx = document.getElementById('gaugeChart').getContext('2d'); var gaugeChart = new Chart(chartCtx, config); </script>
</body> </html>

The above quick example script follows the below steps to render a gauge chart with the data and the options.

Many of the steps are similar to that of creating any other chart using this library. We have seen many examples in the ChartJS library. You can start with the ChartJS bar chart example if you are new to this JavaScript library.

The data and options are the main factors that change the chart view. This section has short notes for more information about the data and the options array created in JavaScript.

This JavaScript example uses an array of static data to form a gauge chart. You can supply dynamic data from the database or any external source instead.

The data array has the chart label, target, and current value. The target value is the maximum limit of the gauge chart scale. The current value is an achieved point to be marked.

Using these values, this script prepares the gauge chart dataset.

The options array is a configuration that affects the chart’s appearance.

The ChartJS allows featured configurations to experience the best chart views. Some of those options exclusive to the gauge chart are listed below.

Posted on Leave a comment

JavaScript – How to Open URL in New Tab

by Vincy. Last modified on June 25th, 2023.

Web pages contain external links that open URLs in a new tab. For example, Wikipedia articles show links to open the reference sites in a new tab. This is absolutely for beginners.

There are three ways to open a URL in a new tab.

  1. HTML anchor tags with target=_blank  attribute.
  2. JavaScript window.open() to set hyperlink and target.
  3. JavaScript code to create HTML link element.

HTML anchor tags with target=_blank  attribute

This is an HTML basic that you are familiar with. I added the HTML with the required attributes since the upcoming JavaScript example works with this base.

<a href="https://www.phppot.com" target="_blank">Go to Phppot</a>

Scenarios of opening URL via JavaScript.

When we need to open a URL on an event basis, it has to be done via JavaScript at run time. For example,

  1. Show the PDF in a new tab after clicking generate PDF link. We have already seen how to generate PDFs using JavaScript.
  2. Show product page from the gallery via Javascript to keep track of the shopping history.

The below two sections have code to learn how to achieve opening URLs in a new tab using JavaScript.

javascript open in new tab

JavaScript window.open() to set hyperlink and target

This JavaScript one-line code sets the link to open the window.open method. The second parameter is to set the target to open the linked URL in a new tab.

window.open('https://www.phppot.com', '_blank').focus();

The above line makes opening a URL and focuses the newly opened tab.

JavaScript code to create HTML link element.

This method follows the below steps to open a URL in a new tab via JavaScript.

  • Create an anchor tag (<a>) by using the createElement() function.
  • Sets the href and the target properties with the reference of the link object instantiated in step 1.
  • Trigger the click event of the link element dynamically created via JS.
var url = "https://www.phppot.com";
var link = document.createElement("a");
link.href = url;
link.target = "_blank";
link.click();

Browsers support: Most modern browsers support the window.open() JavaScript method.

↑ Back to Top

Share this page

Posted on Leave a comment

File Upload using Dropzone with Progress Bar

by Vincy. Last modified on June 30th, 2023.

Most of the applications have the requirement to upload files to the server. In previous articles, we have seen a variety of file upload methods with valuable features.

For example, we learned how to upload files with or without AJAX, validate the uploaded files, and more features.

This tutorial will show how to code for file uploading with a progress bar by Dropzone.

View demo

If the file size is significant, it will take a few nanoseconds to complete. Showing a progress bar during the file upload is a user-friendly approach.

To the extreme, websites start showing the progressing percentage of the upload. It is the best representation of showing that the upload request is in progress.

dropzone progress bar

About Dropzone

The Dropzone is a JavaScript library popularly known for file uploading and related features. It has a vast market share compared to other such libraries.

It provides a massive list of features. Some of the attractive features are listed below.

  • It supports multi-file upload.
  • It represents progressing state and percentage.
  • It allows browser image resizing. It’s a valuable feature that supports inline editing of images.
  • Image previews in the form of thumbnails.
  • It supports configuring the uploaded file’s type and size limit.

How to integrate dropzone.js to upload with the progress bar

Integrating Dropzone into an application is simple. It is all about keeping these two points during the integration.

  1. Mapping the UI element with the Dropzone initiation.
  2. Handling the upload event callbacks effectively.

Mapping the UI element with the Dropzone initiation

The below code has the HTML view to show the Dropzone file upload to the UI. It includes the Dropzone JS and the CSS via a CDN URL.

<!DOCTYPE html>
<html> <head> <title>File Upload using Dropzone with Progress Bar</title> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/dropzone.min.css"> <style> .progress { width: 300px; border: 1px solid #ddd; padding: 5px; } .progress-bar { width: 0%; height: 20px; background-color: #4CAF50; } </style> <link rel="stylesheet" type="text/css" href="style.css" /> <link rel="stylesheet" type="text/css" href="form.css" />
</head> <body> <div class="phppot-container tile-container text-center"> <h2>File Upload using Dropzone with Progress Bar</h2> <form action="upload.php" class="dropzone" id="myDropzone"></form> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/min/dropzone.min.js"></script>
</body> </html>

The file upload form element is mapped to the DropzoneJS while initiating the library.

The form action targets the PHP endpoint to handle the file upload.

Dropzone.options.myDropzone = { //Set upload properties init: function () { // Handle upload event callback functions }; };

Handling the upload event callbacks

This section has the Dropzone library script to include in the view. This script sets the file properties and limits to the upload process. Some of the properties are,

  • maxFilesize – Maximum size allowed for the file to upload.
  • paramName – File input name to access like $_FILE[‘paramName here’].
  • maxFiles – File count allowed.
  • acceptedFiles – File types or extensions allowed.

The init property of this script allows handling the upload event. The event names are listed below.

  • uploadprogress – To track the percentage of uploads to update the progress bar.
  • success – When the file upload request is completed. This is as similar to a jQuery AJAX script‘s success/error callbacks.

Dropzone options have the upload form reference to listen to the file drop event. The callback function receives the upload status to update the UI.

The dropzone calls the endpoint action when dropping the file into the drop area.

The drop area will show thumbnails or a file preview with the progress bar.

Dropzone.options.myDropzone = { paramName: "file", // filename handle to upload maxFilesize: 2, // MB maxFiles: 1, // number of files allowed to upload acceptedFiles: ".png, .jpg, .jpeg, .gif", // file types allowed to upload init: function () { this.on("uploadprogress", function (file, progress) { var progressBar = file.previewElement.querySelector(".progress-bar"); progressBar.style.width = progress + "%"; progressBar.innerHTML = progress + "%"; }); this.on("success", function (file, response) { var progressBar = file.previewElement.querySelector(".progress-bar"); progressBar.classList.add("bg-success"); progressBar.innerHTML = "Uploaded"; }); this.on("error", function (file, errorMessage) { var progressBar = file.previewElement.querySelector(".progress-bar"); progressBar.classList.add("bg-danger"); progressBar.innerHTML = errorMessage; }); } };

PHP file upload script

This a typical PHP file upload script suite for any single file upload request. But, the dependent changes are,

  1. File handle name ($_FILES[‘File handle name’]).
  2. Target directory path for $uploadDir variable.
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) { $file = $_FILES['file']; // file to be uploaded to this directory // should have sufficient file permissions $uploadDir = 'uploads/'; // unique file name generated for the uploaded file $fileName = uniqid() . '_' . $file['name']; // moving the uploaded file from temp directory to uploads directory if (move_uploaded_file($file['tmp_name'], $uploadDir . $fileName)) { echo 'File uploaded successfully.'; } else { echo 'Failed to upload file.'; }
}

How to hide the progress bar of uploaded files

By default, the Dropzone JS callback adds a dz-complete CSS class selector to the dropzone element. It will hide the progress bar from the preview after a successful upload.

This default behavior is by changing the progress bar opacity to 0. But the markup will be there in the source. Element hide and show can be done in various ways.

If you want to remove the progress bar element from the HTML preview, use the JavaScript remove() function. This script calls it for the progress bar element on the success callback.

Dropzone.options.myDropzone = { ... ... init: function () { ... ... this.on("success", function (file, response) { var progressBar = file.previewElement.querySelector(".progress-bar"); progressBar.remove(); }); ... ... }
};

View demo Download

↑ Back to Top

Posted on Leave a comment

AJAX File Upload with Progress Bar using JavaScript

by Vincy. Last modified on June 30th, 2023.

If you want to upload a file using AJAX and also need to show a progress bar during the upload, you have landed on the right page.

This article has an example code for JavaScript AJAX file upload with a progress bar.

An AJAX-based file upload is a repeatedly needed requirement for a web application.

It is for providing an inline editing feature with the uploaded file content. For example, the following tasks can be achieved using the AJAX file upload method.

  1. Photo or banner update on the profile page.
  2. Import CSV or Excel files to load content to the data tables.

View demo
ajax file upload with progress bar javascript

HTML upload form

This HTML shows the input to choose a file. This form has a button that maps its click event with an AJAX handler.

In a previous tutorial, we have seen a jQuery example for uploading form data with a chosen file binary.

But in this example, the HTML doesn’t have any form container. Instead, the form data is created by JavaScript before processing the AJAX.

This HTML has a container to show the progress bar. Once the progress is 100% complete, a success message is added to the UI without page refresh.

<div class="phppot-container tile-container text-center"> <h2>AJAX File Upload with Progress Bar using JavaScript</h2> <input type="file" id="fileUpload" /> <br> <br> <button onclick="uploadFile()">Upload</button> <div class="progress"> <div class="progress-bar" id="progressBar"></div> </div> <br> <div id="uploadStatus"></div>
</div>

AJAX file upload request with progress bar

This section is the core of this example code. This example’s HTML and PHP files are prevalent, as seen in other file upload examples.

The script below follows the steps to achieve the AJAX file upload.

  1. It reads the file binary chosen in the file input field.
  2. It instantiates JavaScript FormData and appends the file binary into it.
  3. It creates an XMLHttpRequest handle.
  4. This handle uses the ‘upload’ property to get XMLHttpRequestUpload object.
  5. This XMLHttpRequestUpload object tracks the upload progress in percentage.
  6. It creates event listeners to update the progressing percentage and the upload status.
  7. Then finally, it posts the file to the PHP endpoint like usual AJAX programming.
function uploadFile() { var fileInput = document.getElementById('fileUpload'); var file = fileInput.files[0]; if (file) { var formData = new FormData(); formData.append('file', file); var xhr = new XMLHttpRequest(); xhr.upload.addEventListener('progress', function (event) { if (event.lengthComputable) { var percent = Math.round((event.loaded / event.total) * 100); var progressBar = document.getElementById('progressBar'); progressBar.style.width = percent + '%'; progressBar.innerHTML = percent + '%'; } }); xhr.addEventListener('load', function (event) { var uploadStatus = document.getElementById('uploadStatus'); uploadStatus.innerHTML = event.target.responseText; }); xhr.open('POST', 'upload.php', true); xhr.send(formData); }
}

PHP endpoint to move the uploaded file into a directory

This PHP  has a standard code to store the uploaded file in a folder using the PHP move_uploaded_file(). The link has the code if you want to store the uploaded file and save the path to the database.

This endpoint creates a unique name for the filename before upload. It is a good programming practice, but the code will work without it, also.

It is for stopping file overwriting in case of uploading different files in the same name.

Note: Create a folder named “uploads” in the project root. Give sufficient write permissions.

<?php if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) { $file = $_FILES['file']; // file will be uploaded to the following folder // you should give sufficient file permissions $uploadDir = 'uploads/'; // unique file name generated $fileName = uniqid() . '_' . $file['name']; // moving the uploaded file from temp location to our target location if (move_uploaded_file($file['tmp_name'], $uploadDir . $fileName)) { echo 'File uploaded successfully.'; } else { echo 'Failed to upload file.'; }
}

View demo Download

↑ Back to Top

Posted on Leave a comment

PHP QR Code Generator with chillerlan-php-qrcode Library

by Vincy. Last modified on June 15th, 2023.

This tutorial will create an example for generating a QR code using PHP. This example uses the Chillerlan QR code library. It is a PHP library with advanced features for creating QR codes, bar codes, and more.

There are two examples in this project. The first is a basic use-case scenario, and the second is an advanced example.

Both will help familiarize this library to send data for QR code rendering.

Quick Example

<?php
require_once '../vendor/autoload.php'; use chillerlan\QRCode\QRCode; // Core class for generating the QR code
$qrCode = new QRCode(); // data for which the QR code will be generated
$data = 'www.phppot.com'; // QR code image generation using render function
// it returns the an image resource.
$qrCodeImage = $qrCode->render($data); // Show the generated QR code image on screen
// following header is necessary to show image output
// in the browser
header('Content-Type: image/png');
imagepng($qrCodeImage);
imagedestroy($qrCodeImage);

The above code is a quick example of generating a Chillerlan QR code. You should use Composer to download the chillerlan dependency.

This example imports the library class and gives the data to generate the QR code.

The render() function passes the data to the library with which it will output the QR code image. This output can be returned to a browser or can be saved as a file.

In a previous article, we learned how to render the generated QR code to the browser.

chillerlan php qrcode

Download via composer

Run the following command in your terminal to install this Chillerlan PHP library.

composer require chillerlan/php-qrcode

qrcode project structure

Example 2 – How to configure size, EC level, scale

More configurations help to adjust the QR code quality without affecting readability.  The below parameters are used, which override the default configurations.

  • The version is to set the size of a QR code.
  • ECC level to set the possible values(L, M, Q, H). It is the damage tolerance percentage. We have seen it when coding with phpqrcode library.
  • Scale sets the size of a QR code pixel. The maximum size increases the QR code’s quality.

This library has the QROptions class to set the configurations explicitly. When initiating this class, the code below prepares an array of {version, eccLeverl …} options.

This QROptions instance generates the QRCode object to call the render() action handler. As in the above example, the render() uses the data and bundles it into the QR code binary.

<?php
require_once '../vendor/autoload.php'; use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions; // data to embed in the QR code image
$data = 'www.phppot.com'; // configuration options for QR code generation
// eccLevel - Error correction level (L, M, Q, H)
// scale - QR code pixe size
// imageBase64 - output as image resrouce or not
$options = new QROptions([ 'version' => 5, 'eccLevel' => QRCode::ECC_H, 'scale' => 5, 'imageBase64' => true, 'imageTransparent' => false, 'foregroundColor' => '#000000', 'backgroundColor' => '#ffffff'
]); // Instantiating the code QR code class
$qrCode = new QRCode($options); // generating the QR code image happens here
$qrCodeImage = $qrCode->render($data); header('Content-Type: image/png');
imagepng($qrCodeImage);
imagedestroy($qrCodeImage);

Chillerlan PHP library

This is one of the popular QR Code generators in PHP. It has clean and easily understandable code with proper modularity.

Some of its features are listed below. This feature list represents the capability of being a component of a PHP application.

Features

  • Creates QR Codes with an improved Model, Version, ECC level, and more configuration
  • It supports encoding numeric, alphanumeric, 8-bit binary, and more.
  • It supports QR code output in GD, ImageMagick, SVG markup, and more formats.
  • It provides QR code readers using GD and ImageMagick libraries.

More about QR code

Hereafter we will see more about the QR code and its evolution,  advantages, and usage scenarios.

The QR code, or the quick response code, is a two-dimensional (2D) bar code. The linked article has the code to generate a barcode using PHP.

The QR code is a Japanese invention for the automotive industry. Later it spreads to more domains. Some of the commonly used places are,

  • Marketing
  • Linking to service providers
  • Information sharing
  • Online payments.

It provides easy access to online information through digital scanners. The QR code contains encoded data that can be decoded with digital scanning. It shares the information, links the service provider or prompts for the payment initiation after scanning.

Example usages of QR code generation and scanning

  • It shows payee details to ensure and allows one to enter the amount to make a mobile payment.
  • It facilitates storing location and contact details. It is for marking locations in the Google map while scanning.
  • When reading the QR code, the application will download v-cards using the contact details stored.
  • The app developing company shows QR codes in the app store to download mobile apps.

Download

↑ Back to Top

Posted on Leave a comment

Web Scraping with PHP – Tutorial to Scrape Web Pages

by Vincy. Last modified on July 21st, 2023.

Web scraping is a mechanism to crawl web pages using software tools or utilities. It reads the content of the website pages over a network stream.

This technology is also known as web crawling or data extraction. In a previous tutorial, we learned how to extract pages by its URL.
View Demo

There are more PHP libraries to support this feature. In this tutorial, we will see one of the popular web-scraping components named DomCrawler.

This component is underneath the PHP Symfony framework. This article has the code for integrating and using this component to crawl web pages.

web scraping php

We can also create custom utilities to scrape the content from the remote pages. PHP allows built-in cURL functions to process the network request-response cycle.

About DomCrawler

The DOMCrawler component of the Symfony library is for parsing the HTML and XML content.

It constructs the crawl handle to reach any node of an HTML tree structure. It accepts queries to filter specific nodes from the input HTML or XML.

It provides many crawling utilities and features.

  1. Node filtering by XPath queries.
  2. Node traversing by specifying the HTML selector by its position.
  3. Node name and value reading.
  4. HTML or XML insertion into the specified container tag.

Steps to create a web scraping tool in PHP

  1. Install and instantiate an HTTP client library.
  2. Install and instantiate the crawler library to parse the response.
  3. Prepare parameters and bundle them with the request to scrape the remote content.
  4. Crawl response data and read the content.

In this example, we used the HTTPClient library for sending the request.

Web scraping PHP example

This example creates a client instance and sends requests to the target URL. Then, it receives the web content in a response object.

The PHP DOMCrawler parses the response data to filter out specific web content.

In this example, the crawler reads the site title by parsing the h1 text. Also, it parses the content from the site HTML filtered by the paragraph tag.

The below image shows the example project structure with the PHP script to scrape the web content.

web scraping php project structure

How to install the Symfony framework library

We are using the popular Symfony to scrape the web content. It can be installed via Composer.
Following are the commands to install the dependencies.

composer require symfony/http-client symfony/dom-crawler
composer require symfony/css-selector

After running these composer commands, a vendor folder can map the required dependencies with an autoload.php file. The below script imports the dependencies by this file.

index.php

<?php require 'vendor/autoload.php'; use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\DomCrawler\Crawler; $httpClient = HttpClient::create(); // Website to be scraped
$website = 'https://example.com'; // HTTP GET request and store the response
$httpResponse = $httpClient->request('GET', $website);
$websiteContent = $httpResponse->getContent(); $domCrawler = new Crawler($websiteContent); // Filter the H1 tag text
$h1Text = $domCrawler->filter('h1')->text();
$paragraphText = $domCrawler->filter('p')->each(function (Crawler $node) { return $node->text();
}); // Scraped result
echo "H1: " . $h1Text . "\n";
echo "Paragraphs:\n";
foreach ($paragraphText as $paragraph) { echo $paragraph . "\n";
}
?>

Ways to process the web scrapped data

What will people do with the web-scraped data? The example code created for this article prints the content to the browser. In an actual application, this data can be used for many purposes.

  1. It gives data to find popular trends with the scraped news site contents.
  2. It generates leads for showing charts or statistics.
  3. It helps to extract images and store them in the application’s backend.

If you want to see how to extract images from the pages, the linked article has a simple code.

Caution

Web scraping is theft if you scrape against a website’s usage policy.  You should read a website’s policy before scraping it. If the terms are unclear, you may get explicit permission from the website’s owner. Also, commercializing web-scraped content is a crime in most cases. Get permission before doing any such activities.

Before crawling a site’s content, it is essential to read the website terms. It is to ensure that the public can be subject to scraping.

People provide API access or feed to read the content. It is fair to do data extraction with proper API access provision. We have seen how to extract the title, description and video thumbnail using YouTube API.

For learning purposes, you may host a dummy website with lorem ipsum content and scrape it.
View Demo

↑ Back to Top

Posted on Leave a comment

Top 7 Ways to Use Auto-GPT Tools in Your Browser

5/5 – (1 vote)

Installing Auto-GPT is not simple, especially if you’re not a coder, because you need to set up Docker and do all the tech stuff. And even if you’re a coder you may not want to go through the hassle. In this article, I’ll show you some easy Auto-GPT web interfaces that’ll make the job easier!

Tool #1 – Auto-GPT on Hugging Face

Hugging Face user aliabid94 created an Auto-GPT web interface (100% browser-based) where you can put in your OpenAI API key and try out Auto-GPT in seconds.

To get an OpenAI API key, check out this tutorial on the Finxter blog or visit your paid OpenAI account directly here.

The example shows the Auto-GPT run of an Entrepreneur-GPT that is designed to grow your Twitter account. 💰😁

Tool #2 – AutoGPTJS.com

I haven’t tried autogptjs.com but the user interface looks really compelling and easy to use. Again, you need to enter your OpenAI API key and you should create a new one and revoke it after use. Who knows where the keys are really stored?

Well, this project looks trustworthy as it’s also available on GitHub.

Tool #3 – AgentGPT

AgentGPT is an easy-to-use browser based autonomous agent based on GPT-3.5 and GPT-4. It is similar to Auto-GPT but uses its own repository and code base.

I have written a detailed comparison between Auto-GPT and AgentGPT on the Finxter blog but the TLDR is that it’s easier to setup and use at the cost of being much more expensive and less suitable for long-running tasks.

Tool #4 – AutoGPT UI with Nuxt.js

AutoGPT UI, built with Nuxt.js, is a user-friendly web tool for managing AutoGPT workspaces. Users can easily upload AI settings and supporting files, adjust AutoGPT settings, and initiate the process via our intuitive GUI. It supports both individual and multi-user workspaces. Its workspace management interface enables easy file handling, allowing drag-and-drop features and seamless interaction with source or generated content.

Some More Comments… 👇

Before you go, here are a few additional notes.

Token Usage and Revoking Keys

To access Auto-GPT, you need to use the OpenAI API key, which is essential for authenticating your requests. The token usage depends on the API calls you make for various tasks.

You should set a spending limit and revoke your API keys after putting them in any browser-based Auto-GPT tool. After all, you don’t know where your API keys will end up so I use a strict one-key-for-one-use policy and revoke all keys directly after use.

3 More Tools

The possibilities with Auto-GPT innovation are vast and ever-expanding.

For instance, researchers and developers are creating new AI tools such as Godmode (I think it’s based on BabyAGI) to easily deploy AI agents directly in the web browser.

With its potential to grow and adapt, Auto-GPT is poised to make an impact on numerous industries, driving further innovation and advancements in AI applications.

🌐 AutoGPT Chrome extension is another notable add-on, providing an easily accessible interface for users.

Yesterday I found a new tool called JARVIS (HuggingGPT), named after the J.A.R.V.I.S. artificial intelligence from Ironman, that is an Auto-GPT alternative created by Microsoft research that uses not only GPT-3.5 and GPT-4 but other LLMs as well and is able to generate multimedia output such as audio and images (DALL-E). Truly mindblowing times we’re living in.

🤖 Recommended: Auto-GPT vs Jarvis HuggingGPT: One Bot to Rule Them All