#in_array()
Explore tagged Tumblr posts
pentesttestingcorp · 4 months ago
Text
How to Prevent Unvalidated Redirects and Forwards in Laravel
Introduction
When developing a Laravel application, security should be a top priority. One of the most common vulnerabilities that can put your users at risk is unvalidated redirects and forwards. These vulnerabilities occur when a user is redirected or forwarded to an untrusted URL without proper validation, which can be exploited by attackers to conduct phishing, session fixation, or other malicious activities.
Tumblr media
In this blog post, we'll discuss how to identify and prevent unvalidated redirects and forwards in your Laravel applications, including practical coding examples and tips to enhance the security of your website.
What Are Unvalidated Redirects and Forwards?
An unvalidated redirect occurs when a user is sent to a URL that isn't properly checked for trustworthiness. For example, an attacker may trick a user into clicking a link that redirects them to a malicious site.
Similarly, unvalidated forwards happen when the application forwards a user to another resource without proper validation. Attackers can exploit this to bypass security checks or perform unauthorized actions.
Why Are They Dangerous?
Both unvalidated redirects and forwards can be exploited by attackers for various malicious purposes, including:
Phishing attacks: Redirecting users to fake websites to steal their personal information.
Session hijacking: Redirecting users to a page that steals their session data.
Malicious data exposure: Forwards to unauthorized resources.
How to Prevent Unvalidated Redirects and Forwards in Laravel
1. Use Laravel's Built-in Validation for Redirects
One of the simplest ways to avoid these vulnerabilities is to validate URLs before redirecting users. Laravel has a built-in url() method to ensure that the redirect URL is valid and within the allowed domain.
Here’s how you can implement a secure redirect:
use Illuminate\Support\Facades\Redirect; public function redirectToInternalPage($path) { $validPaths = ['/home', '/dashboard', '/profile']; // Allowed paths if (in_array($path, $validPaths)) { return Redirect::to($path); } else { return abort(403, 'Unauthorized redirect.'); } }
This approach ensures that users can only be redirected to predefined paths within your application.
2. Validate External Redirects
If your application needs to redirect users to external URLs, ensure that the redirect destination is trusted. A basic way to achieve this is by checking if the destination URL belongs to a trusted domain:
use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Str; public function redirectToExternalSite($url) { $trustedDomains = ['trustedsite.com', 'anothertrusted.com']; $host = parse_url($url, PHP_URL_HOST); if (in_array($host, $trustedDomains)) { return Redirect::to($url); } else { return abort(403, 'Untrusted redirect destination.'); } }
This will prevent users from being redirected to malicious websites, as the app only allows URLs from trusted domains.
3. Implement URL Whitelisting
Another preventive measure is to implement URL whitelisting. This approach limits the URLs that users can be redirected to, ensuring that they are only sent to trusted destinations.
public function validateRedirect($url) { $whitelistedUrls = ['https://example.com', 'https://secure.com']; if (in_array($url, $whitelistedUrls)) { return Redirect::to($url); } else { return redirect('/home')->with('error', 'Invalid redirect attempt.'); } }
4. Use Redirect::secure() for HTTPS Redirects
To avoid redirection to unsecure HTTP links, always use secure redirects. You can ensure that the user is redirected to a secure HTTPS URL by using Redirect::secure():
return Redirect::secure('/dashboard');
This method forces the redirect to be on an HTTPS connection, enhancing the security of your application.
Preventing Vulnerabilities with Tools
It’s essential to regularly assess your website’s security. For that, you can use our Free Website Security Scanner tool to identify vulnerabilities like unvalidated redirects and forwards.
Visit our tool to get started. Below is a screenshot of the tool's homepage for your reference.
Tumblr media
Additionally, after running a scan, you will receive a detailed vulnerability assessment report to check Website Vulnerability, helping you pinpoint areas that need attention.
Tumblr media
Conclusion
Unvalidated redirects and forwards are serious security vulnerabilities that can jeopardize your Laravel application. By following the methods outlined in this post, you can secure your application and protect your users from phishing, session fixation, and other malicious activities.
Remember to keep your Laravel application up to date and utilize our free tool for Website Security tests to conduct regular assessments and stay ahead of potential threats.
For more tips and tutorials on securing your Laravel application, visit our blog at Pentest Testing Corp Blog.
2 notes · View notes
fromdevcom · 5 months ago
Text
Supercharge Your WordPress Development with These 10 PHP Snippets WordPress powers over 40% of the web, making it one of the most popular platforms for developers and bloggers alike. Whether you're customizing themes, building plugins, or tweaking functionality, having a handy set of PHP code snippets can save you hours of work. Here are 10 practical PHP snippets every WordPress developer should keep in their toolkit. 1. Disable WordPress Admin Bar for Non-Admins The admin bar can clutter the frontend for non-admin users. Use this snippet to disable it for everyone except administrators: add_action('after_setup_theme', function() if (!current_user_can('administrator')) show_admin_bar(false); ); This ensures a clean frontend experience for subscribers and other roles. 2. Change Default Login Logo URL Customizing the WordPress login page is a common requirement. Use this snippet to change the logo URL on the login screen: add_filter('login_headerurl', function() return home_url(); // Redirect to your website's homepage ); Combine this with CSS to fully brand the login page for clients or personal projects. 3. Redirect Users After Login Based on Role Direct users to specific pages after login based on their roles: add_filter('login_redirect', function($redirect_to, $request, $user) if (isset($user->roles) && is_array($user->roles)) if (in_array('administrator', $user->roles)) return admin_url(); elseif (in_array('editor', $user->roles)) return home_url('/editor-dashboard'); else return home_url('/welcome'); return $redirect_to; , 10, 3); This snippet improves user navigation and role-specific workflows. 4. Custom Excerpt Length Control the excerpt length in posts to maintain a consistent look across your site: add_filter('excerpt_length', function($length) return 20; // Set the excerpt length to 20 words ); Pair this with a custom read more link for better UX: add_filter('excerpt_more', function() return '... Read More'; ); 5. Remove WordPress Version Number Hiding the WordPress version number improves security by making it harder for attackers to target vulnerabilities: remove_action('wp_head', 'wp_generator'); This simple snippet removes the version meta tag from the HTML source. 6. Add Custom Image Sizes Define and use custom image sizes for different parts of your theme: add_action('after_setup_theme', function() add_image_size('custom-thumb', 400, 300, true); // Cropped image size ); To use this image size in your theme: echo wp_get_attachment_image($attachment_id, 'custom-thumb'); 7. Disable WordPress Auto Updates Sometimes you want to disable automatic updates to maintain more control: add_filter('automatic_updater_disabled', '__return_true'); You can also disable specific updates, such as plugin updates: add_filter('auto_update_plugin', '__return_false'); 8. Custom Maintenance Mode Display a maintenance mode page while working on your site: add_action('template_redirect', function() if (!current_user_can('administrator') && !is_user_logged_in()) wp_die( 'Under MaintenanceWe’ll be back shortly!', 'Maintenance Mode', array('response' => 503) ); ); This ensures only admins can access the site during maintenance. 9. Limit Post Revisions Restrict the number of post revisions saved in the database to optimize performance: define('WP_POST_REVISIONS', 5); // Limit to 5 revisions per post Add this line to your wp-config.php file to apply globally. 10. Custom Dashboard Widget Add a custom widget to the WordPress admin dashboard for quick links or messages: add_action('wp_dashboard_setup', function() wp_add_dashboard_widget( 'custom_dashboard_widget', 'Welcome to Your Dashboard',
function() echo 'Need help? Visit our support center.'; ); ); This snippet is great for client sites where you can provide tailored guidance. Wrapping Up These 10 PHP snippets cover some of the most common tasks WordPress developers encounter. By incorporating these into your workflow, you’ll save time and enhance the functionality of your projects. Bookmark this cheat sheet and customize these snippets to suit your specific needs!
0 notes
web-realm-9 · 8 months ago
Text
Enhances image quality by setting the JPEG compression quality to high.
Sets the JPEG quality to 100% for high quality.
Converts JPEG and PNG images to WebP upon upload.
functions.php
// Set image quality to highadd_filter('jpeg_quality', function() { return 100; });// Convert uploaded images to WebPfunction convert_to_webp($metadata, $attachment_id) { $upload_dir = wp_upload_dir(); $file_path = $upload_dir['basedir'] . '/' . $metadata['file']; $info = pathinfo($file_path); // Check if file is an image if (in_array(strtolower($info['extension']), ['jpg', 'jpeg', 'png'])) { $webp_file = $info['dirname'] . '/' . $info['filename'] . '.webp'; if ($info['extension'] == 'png') { $image = imagecreatefrompng($file_path); imagepalettetotruecolor($image); imagewebp($image, $webp_file, 80); imagedestroy($image); } else { $image = imagecreatefromjpeg($file_path); imagewebp($image, $webp_file, 80); imagedestroy($image); } // Update the metadata to point to the WebP version $metadata['file'] = str_replace($info['basename'], $info['filename'] . '.webp', $metadata['file']); } return $metadata;}add_filter('wp_generate_attachment_metadata', 'convert_to_webp', 10, 2);// Add title and description based on filenamefunction auto_add_image_title_desc($post_ID) { $attachment = get_post($post_ID); $filename = pathinfo(get_attached_file($post_ID), PATHINFO_FILENAME); if (empty($attachment->post_title)) { $title = str_replace(['-', '_'], ' ', $filename); wp_update_post([ 'ID' => $post_ID, 'post_title' => ucwords($title), 'post_content' => 'Image titled: ' . ucwords($title) ]); }}add_action('add_attachment', 'auto_add_image_title_desc');
find more:
1 note · View note
phptrainingtrickstips · 2 years ago
Text
Array manipulation in PHP
PHP Certification Course, Array manipulation in PHP involves performing various operations on arrays, such as adding or removing elements, sorting, searching, and restructuring. PHP offers a rich set of array functions to facilitate these tasks. Here are some common array manipulation techniques:
Creating Arrays: Arrays in PHP can be created using square brackets [] or the array() construct. For example:phpCopy code$numbers = [1, 2, 3, 4, 5]; $fruits = array('apple', 'banana', 'cherry');
Adding Elements: To add elements to an array, you can use the assignment operator = or the [] notation. For example:phpCopy code$numbers[] = 6; // Adds 6 to the end of the $numbers array array_push($fruits, 'date'); // Adds 'date' to the end of the $fruits array
Removing Elements: Elements can be removed using functions like unset() or array manipulation functions like array_pop() and array_shift(). For example:phpCopy codeunset($numbers[2]); // Removes the element at index 2 $removedFruit = array_shift($fruits); // Removes and returns the first element
Merging Arrays: Arrays can be combined using functions like array_merge() or the + operator. For example:phpCopy code$combinedArray = array_merge($numbers, $fruits); $mergedArray = $numbers + $fruits; // Note: Keys are preserved
Sorting Arrays: Arrays can be sorted using functions like sort(), rsort(), asort(), ksort(), etc., based on different criteria such as value or key. For example:phpCopy codesort($numbers); // Sorts the array in ascending order ksort($fruits); // Sorts the array by keys
Searching in Arrays: Functions like in_array() and array_search() can be used to search for elements in an array. For example:phpCopy code$found = in_array('banana', $fruits); // Checks if 'banana' is in the $fruits array $index = array_search('cherry', $fruits); // Returns the index of 'cherry' in $fruits
Filtering Arrays: Functions like array_filter() allow you to create a new array with elements that meet specific criteria. For example:phpCopy code$filteredNumbers = array_filter($numbers, function($num) { return $num % 2 == 0; // Filters even numbers });
Iterating Over Arrays: Looping constructs like foreach and for are commonly used to iterate through arrays and perform operations on each element.
These are just a few examples of array manipulation techniques in PHP. Understanding these functions and techniques allows developers to effectively work with and manipulate arrays in their applications.
0 notes
vinhjacker1 · 2 years ago
Text
Filling a PHP array dynamically means that instead of hardcoding the values, you're adding values to the array based on some logic, external input, or data sources. Here's a basic overview and some examples:
1. Create an Empty Array
You can create an empty array using the 'array()' function or the '[]' shorthand.
$dynamicArray = array(); // OR $dynamicArray = [];
2. Add Elements to the Array
You can add elements to an array in various ways:
Append to the array:
$dynamicArray[] = 'value1'; $dynamicArray[] = 'value2';
Add with a specific key:
$dynamicArray['key1'] = 'value1'; $dynamicArray['key2'] = 'value2';
3. Dynamically Filling the Array
Here's how you can fill an array based on various scenarios:
From a database (using PDO for this example)
$stmt = $pdo->query("SELECT value FROM some_table"); while ($row = $stmt->fetch()) { $dynamicArray[] = $row['value']; }
From a form (using POST method as an example):
if (isset($_POST['inputName'])) { $dynamicArray[] = $_POST['inputName']; }
Based on some logic:
for ($i = 0; $i < 10; $i++) { if ($i % 2 == 0) { $dynamicArray[] = $i; } }
This would fill $dynamicArray with even numbers between 0 and 9.
4. Tips and Best Practices
Sanitize external input: Always sanitize and validate data, especially when it's coming from external sources like user input, to ensure security.
Use associative arrays wisely: If you're using string keys, ensure they're unique to avoid overwriting values.
Check existing values: When adding to an array, you may want to check if a value already exists to avoid duplicates.
if (!in_array($value, $dynamicArray)) { $dynamicArray[] = $value; }
Using these methods and principles, you can effectively and dynamically fill a PHP array based on any set of conditions or data sources.
0 notes
positronx · 6 years ago
Link
0 notes
yourblogcoach1 · 4 years ago
Link
Check the most useful PHP functions like:
is_array($arr) in_array($search, $arr, $type) sizeof($arr) array_merge($arr1, $arr2) array_keys($arr) array_values($arr) array_push($arr, $val) array_pop($arr) . . . more
0 notes
webappuser · 2 years ago
Text
Learn the Laravel Array Helper Function
Are you looking to optimize your Laravel workflow? If so, then you’ve come to the right place. In this article, We will show you the Laravel Array Helper Function and how it can help make your coding experience that much better. The Laravel Array Helper Function is an extremely powerful tool that allows developers to access, manipulate and iterate through arrays in a clean and efficient way. We’ll discuss what it is, why it’s useful and how you can use it to maximize your productivity levels. So without further ado, let’s get started!
Tumblr media
What is the Laravel Array Helper Function?
The Laravel array helper function is a great way to manage your arrays. It can help you keep track of your array keys and values, and even sort them by key or value. You can also use it to merge two or more arrays together, and even do some basic math on your arrays.
The Different Types of Arrays
Arrays are data structures that store one or more values in a single variable. There are many different types of arrays, each with their own advantages and disadvantages. The most common type of array is the linear array, which stores values in a single row or column. Laravel Arr Helper are easy to create and use, but they are not very efficient for large amounts of data.
The next most common type of array is the two-dimensional array, which stores values in a table with rows and columns. Two-dimensional arrays are more efficient than linear arrays for large amounts of data, but they are more difficult to create and use.
The last type of array is the three-dimensional array, which stores values in a cube with rows, columns, and layers. Three-dimensional arrays are the most efficient for large amounts of data, but they are the most difficult to create and use.
What are the Benefits of Using the Laravel Array Helper Function?
There are many benefits to using the laravel helper arr function. Some of these benefits include:
-Laravel is a great tool for managing arrays and objects. The Array Helper function makes it easy to work with arrays in Laravel.
-The Array Helper function can be used to fetch data from an external API. This is helpful if you need to display data on your website that is not stored in your database.
-The Array Helper function can be used to sort data. This is helpful if you need to display data on your website in a specific order.
-The Array Helper function can be used to filter data. This is helpful if you need to display only certain data on your website.
You Can Also Check - Out :
laravel eloquent where child
laravel parent child relationship
 
How to Use the Laravel Array Helper Function
Laravel's array helper function is a great way to quickly manipulate arrays of data. In this article, we'll show you how to use the array helper function to perform various tasks.
First, let's take a look at how to use the array helper function to sort an array. To sort an array, simply pass the array as the first argument to the array_helper function. The second argument is the sorting order, which can be either "asc" or "desc". For example, to sort an array in ascending order, you would use the following code:
array_helper( $array, 'asc' );
To sort an array in descending order, you would use the following code:
array_helper( $array, 'desc' );
Now that we know how to sort an array using the array helper function, let's take a look at how to search an array for a specific value. To search an array for a specific value, we'll use the in_array function. The in_array function takes two arguments: The first argument is the value that you're searching for; The second argument is the array that you want to search. For example, let's say we have an array of numbers and we want to know if 5 is in that array. We could use the following code:
in_array( 5, $numbers ); //Returns true or false
Conclusion
We have discussed the Laravel array helper functions and how they can be used in a variety of scenarios. We hope this information has been helpful for you as you dive into using the Laravel framework to build powerful web applications. Remember, if you are ever stuck, our team at Webappfix is here to help! Good luck on your journey with Laravel!
0 notes
blog-by-raika · 3 years ago
Text
【 PHP 】PHP8に入門してみた 118日目 PHPの基本 ( 組み込み関数 配列内の存在確認 )
【 PHP 】PHP8に入門してみた 118日目 PHPの基本 ( 組み込み関数 配列内の存在確認 )
PHP8技術者認定初級試験 が始まるようなので 試験に向けて (できるだけ)勉強しようと思います! 使用する書籍は独習PHP 第4版(山田 祥寛)|翔泳社の本 (shoeisha.co.jp) となりま��。 組み込み関数 要素が存在するか確認する in_array関数 「要素が存在するかしないか」を、知りたいならばin_arrayを使えます。 ただし、この関数はヒットした要素が「1件目(インデックス0)」の場合は存在するにも関わらず、falseと判定されてしまいます。 理由は簡単です。PHPでは数値の0はfalseとして扱われてしまうためです。 <!DOCTYPE html> <html lang="ja"> <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width,…
Tumblr media
View On WordPress
0 notes
cdevroe · 3 years ago
Text
Trying to use PHP’s in_array() on ~300,000 elements. Where I would expect there to be a huge number of elements found, I’m getting none. Is it just choking? Anyone have experience with this size of a lookup?
0 notes
pentesttestingcorp · 1 month ago
Text
Open Redirect Vulnerability in Symfony: How to Detect & Fix
Open Redirect vulnerability is a common security flaw that can affect web applications built with Symfony. It occurs when a web application accepts a user-controlled input that specifies a URL and redirects the user to that URL without proper validation. Attackers exploit this to redirect victims to malicious websites, phishing pages, or malware downloads, causing reputational damage and security risks.
Tumblr media
In this article, we'll explain what Open Redirect vulnerabilities are, how they manifest in Symfony apps, and how to prevent them with clear coding examples. We’ll also showcase how you can use our free Website Security Scanner to scan your website for such vulnerabilities.
What is Open Redirect Vulnerability?
An Open Redirect occurs when an application redirects users to a URL specified via user input without adequate validation. This can be exploited by attackers to craft URLs that look legitimate but redirect users elsewhere, facilitating phishing attacks or malware distribution.
Example Scenario:
https://example.com/redirect?url=http://malicious-site.com
If the app blindly redirects the user to the url parameter, it’s vulnerable.
How Open Redirect Happens in Symfony
Symfony applications typically use the redirect() method or RedirectResponse class to handle URL redirections. A common mistake is to redirect using a user-supplied URL parameter without sanitization or validation.
Vulnerable Symfony Code Example
// src/Controller/RedirectController.php namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\Routing\Annotation\Route; class RedirectController extends AbstractController { /** * @Route("/redirect", name="app_redirect") */ public function redirectToUrl(Request $request) { $url = $request->query->get('url'); // Vulnerable: redirecting directly to user input return new RedirectResponse($url); } }
If an attacker sends a URL like: https://yourdomain.com/redirect?url=http://evil-site.com users will be redirected without warning.
How to Prevent Open Redirect in Symfony
1. Validate URLs Against a Whitelist
Only allow redirects to trusted URLs or paths.
public function redirectToUrl(Request $request) { $allowedDomains = ['yourdomain.com', 'trustedpartner.com']; $url = $request->query->get('url'); $parsedUrl = parse_url($url); $host = $parsedUrl['host'] ?? ''; if (!in_array($host, $allowedDomains)) { // Redirect to homepage if URL is not allowed $url = $this->generateUrl('homepage'); } return new RedirectResponse($url); }
2. Use Relative Paths Instead of Full URLs
Avoid allowing full URLs, prefer relative paths within your app.
public function redirectToPath(Request $request) { $path = $request->query->get('path'); // Validate path format (e.g., starts with '/') if (strpos($path, '/') !== 0) { $path = '/'; } return $this->redirect($path); }
Detect Open Redirect Using Our Free Website Vulnerability Scanner
We developed a free and easy-to-use Website Vulnerability Scanner available at:
Tumblr media
Screenshot: Free Website Security Checker tool homepage.
This tool scans your website for common vulnerabilities including Open Redirects, Cross-Site Scripting (XSS), SQL Injection, and more. It generates a detailed vulnerability assessment report to check Website Vulnerability like the one shown below:
Tumblr media
Screenshot: Sample vulnerability assessment report from our free tool.
You can test your Symfony-based sites or any web applications for Open Redirect vulnerabilities in seconds, and get actionable remediation tips.
Why Open Redirect Matters: Risks and Impact
Phishing Attacks: Attackers lure users to malicious sites via trusted URLs.
Loss of User Trust: Users lose confidence if your site redirects to suspicious destinations.
SEO Penalties: Search engines may penalize sites used for malicious redirects.
Legal Consequences: Compliance issues if users are harmed via redirects.
Additional Resources
For more in-depth cybersecurity insights and tutorials, visit our blog at Pentest Testing Corp.
Secure Your Symfony App with Professional Testing Services
While tools help detect vulnerabilities, professional Web Application Penetration Testing can uncover deep security flaws. We offer expert penetration testing services designed for Symfony and other frameworks.
Explore our service: Web App Penetration Testing Services
Stay Updated with Security Trends
Subscribe to our newsletter on LinkedIn to get the latest cybersecurity updates, vulnerability news, and exclusive tips: Subscribe on LinkedIn
Conclusion
Open Redirect vulnerabilities can easily slip into Symfony applications if user inputs are not properly validated before redirection. Use safe coding practices such as whitelisting trusted domains and restricting redirects to relative paths. Regularly scan your website with tools like our free Website Security Checker at https://free.pentesttesting.com/.
If you want to ensure your app’s security at a deeper level, consider our professional penetration testing services. Stay vigilant and keep your users safe!
If you enjoyed this post or found it helpful, please share it on your social channels and follow our blog at Pentest Testing Blog.
1 note · View note
winmundo · 3 years ago
Text
Win Mundo – Technical Question and Answer Forum
Importerror: Install Xlrd >= 0.9.0 For Excel Support
Importerror: Cannot Import Name ‘Abs’
Attributeerror: ‘Module’ Object Has No Attribute ‘Ssl_St_Init’
Typeerror: ‘Instancemethod’ Object Is Not Iterable
Preg_Match In Javascript
Python Comment Multiple Lines Shortcut Pycharm
No Module Named Win32Com.Client
Javascript In_Array
Command “Python Setup.Py Egg_Info” Failed With Error Code 1 Xgboost
1 note · View note
blogdeprogramacion · 7 years ago
Text
Importar un Excel a MySql con PHP
Importar un Excel a MySql con PHP aparece primero en nuestro https://jonathanmelgoza.com/blog/importar-un-excel-a-mysql-con-php/
Tumblr media
¿Necesitas importar masivamente información a mysql? ¿Necesitas agregar esta funcionalidad a tus proyectos web? Hoy vamos a ver un ejemplo práctico para importar un excel a mysql con php y la libreria SpreadSheet Reader, serán archivos de excel xls o xlsx y no formatos conflictivos como CSV.
Muchas veces en nuestros proyectos web o sistemas en la nube manejamos pequeños catálogos de información.
Nuestros usuarios deben de llenar la información al comenzar a utilizar su sistema lo cual se vuelve una tarea un poco molesta para ellos.
Es por esto que nos suelen pedir algun tipo de ayuda o función para que ellos llenen un excel y el sistema sea capaz de leer la información.
Hoy vamos a ver como importar un excel a mysql con php y SpreadSheet Reader.
Requerimientos
Antes de comenzar necesitamos descargarnos la librería de SpreadSheet Reader:
Web Oficial
Mi servidor
Obviamente también necesitaremos:
Servidor PHP
Excel
Teniendo los requerimientos vamos primeramente con la pantalla para seleccionar el formato excel.
Solicitar formato de excel
Necesitamos una pantalla para permitir a los usuarios de nuestro sistema subir el formato excel necesario con la información.
Para esto haremos uso de un formulario que manda la información via POST a un archivo php llamado subirFormatoProveedores.php que veremos más adelante.
Toma nota de los nombres de los input y que solo permitimos subir archivos xls y xlsx.
<div id="areaSubirFormato"> <form action="database/subirFormatoProveedores.php" method="post" enctype="multipart/form-data"> <p> <input type="submit" name="submit" value="Subir" accept=".xls,.xlsx" /> <input type="file" name="file" /> </p> </form> <p> <a href="files/formato-proveedores.xlsx" download> <i class="fa fa-download" aria-hidden="true"></i> Descargar formato </a> </p> </div>
Como puedes ver en el segundo parrafo incluyo un enlace de descarga para que puedan descargar el formato vacio con los nombres de las columnas, te sugiero hacer lo mismo.
Dejo en tus manos añadir algo de estilo a esta precaria interfaz, para no agregar codigo innecesario no pondré CSS en este tutorial.
Procesar información del excel con SpreadSheet Reader
En nuestro archivo subirFormatoProveedores.php lo primero que haremos será incluir nuestro archivo de conexion a base de datos o en su defecto realizar la conexión a MySql.
También necesitaremos incluir el archivo excel_reader2.php y SpreadSheetReader.php de nuestra librería para leer archivos Excel que descargamos anteriormente.
require_once('excel/php-excel-reader/excel_reader2.php'); require_once('excel/SpreadsheetReader.php');
Posteriormente haremos algunas tareas básicas:
if( isset($_POST["submit"]) ){ $error = false; $allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']; if(in_array($_FILES["file"]["type"],$allowedFileType)){
Y subimos el archivo:
$ruta = "formatos/" . $_FILES['file']['name']; move_uploaded_file($_FILES['file']['tmp_name'], $ruta);
Inicializamos SpreadSheetReader:
$Reader = new SpreadsheetReader($ruta);
Y comenzamos lo bueno:
$sheetCount = count($Reader->sheets()); for($i=0;$i<$sheetCount;$i++) $Reader->ChangeSheet($i); $primera = true; foreach ($Reader as $Row) // Evitamos la primer linea if($primera) $primera = false; continue; // Obtenemos informacion $campo1= ""; if(isset($Row[0])) $campo1= mysqli_real_escape_string($conn,$Row[0]); $campo2= ""; if(isset($Row[1])) $campo2= mysqli_real_escape_string($conn,$Row[1]); ... .. . // Guardamos en base de datos // En siguiente sección
Bastante fácil no crees?
Vamos a ir leyendo fila por fila y preparamos la información para su inserción en base de datos, lo cual haremos ahora mismo en el siguiente tema.
Guardando los registros a base de datos
Ahora la parte que quedo pendiente, guardar en base de datos cada fila que vamos leyendo de nuestro excel.
// Guardamos en base de datos if (!empty($campo1) || !empty($campo2)) $query = "insert into tabla(campo1,campo2, ...) values('".$campo1."','".$campo2."',...)"; $result = mysqli_query($conn, $query); if (empty($result)) $error = true;
Como puedes ver esta es la parte más fácil de este post sobre como importar un excel a mysql y mira que no ha sido dificil.
Perfecto! Hemos terminado.
Si este post te fue de utilidad no olvides compartirla en tus redes sociales o dejarnos un comentario si tienes alguna duda respecto a importar un excel a mysql con php y SpreadSheet Reader.
Hasta luego!
3 notes · View notes
developerdiary · 3 years ago
Text
0 notes
hschneider66 · 4 years ago
Link
0 notes
pintire · 5 years ago
Text
Check if values are exists in Array – jQuery and JavaScript
If you are familiar with PHP, where you can use the in_array() function to search value in the Array, and it returns the Boolean value ( TRUE or FALSE ) to Check if values…
0 notes