Posts

Showing posts with the label Php

CodeIgniter Htaccess And URL Rewrite Issues

Answer : There are 3 steps to remove index.php . Make below changes in application/config.php file $config['base_url'] = 'http://'.$_SERVER['SERVER_NAME'].'/Your Ci folder_name'; $config['index_page'] = ''; $config['uri_protocol'] = 'AUTO'; Make .htaccess file in your root directory using below code RewriteEngine on RewriteCond $1 !^(index\.php|resources|robots\.txt) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L,QSA] Enable the rewrite engine (if not already enabled) i. First, initiate it with the following command: a2enmod rewrite ii. Edit the file /etc/apache2/sites-enabled/000-default Change all AllowOverride None to AllowOverride All . Note: In latest version you need to change in /etc/apache2/apache2.conf file iii. Restart your server with the following command: sudo /etc/init.d/apache2 restart Your .htaccess is slightly o...

Codeigniter - Date Format - Form Validation

Answer : You can take use of CodeIgniters callback functions by creating a callback_date_valid() function that check if the date is valid. And to check if it is valid, you could use PHP's checkdate function array( 'field' => 'reg[dob]', 'label' => 'DOB', 'rules' => 'required|date_valid' ) function callback_date_valid($date){ $day = (int) substr($date, 0, 2); $month = (int) substr($date, 3, 2); $year = (int) substr($date, 6, 4); return checkdate($month, $day, $year); } I have a pretty clean solution for this. You can extend codeigniters form validation library. Do this by putting a MY_Form_validation.php file in your application/libraries folder. This file should look like this: class MY_Form_validation extends CI_Form_validation { public function __construct($rules = array()) { parent::__construct($rules); } public function valid_date($date) { $d = DateTime:...

Abstract Constants In PHP - Force A Child Class To Define A Constant

Answer : This may be a bit of a ‘hack’, but does the job with very little effort, but just with a different error message if the constant is not declared in the child class. A self-referential constant declaration is syntactically correct and parses without problem, only throwing an error if that declaration is actually executed at runtime, so a self-referential declaration in the abstract class must be overridden in a child class else there will be fatal error: Cannot declare self-referencing constant . In this example, the abstract, parent class Foo forces all its children to declare the variable NAME . This code runs fine, outputting Donald . However, if the child class Fooling did not declare the variable, the fatal error would be triggered. <?php abstract class Foo { // Self-referential 'abstract' declaration const NAME = self::NAME; } class Fooling extends Foo { // Overrides definition from parent class // Without this declaration, an ...

Add A Custom Stock Status In WooCommerce

Answer : for anyone interested, here is complete solution, based on Laila's approach. Warning! My solution is intended to work only with WooCommerce "manage stock" option disabled ! I am not working with exact amounts of items in stock. All code goes to functions.php , as usual. Back-end part Removing native stock status dropdown field. Adding CSS class to distinguish my new custom field. Dropdown has now new option "On Request". function add_custom_stock_type() { ?> <script type="text/javascript"> jQuery(function(){ jQuery('._stock_status_field').not('.custom-stock-status').remove(); }); </script> <?php woocommerce_wp_select( array( 'id' => '_stock_status', 'wrapper_class' => 'hide_if_variable custom-stock-status', 'label' => __( 'Stock status', 'woocommerce' ), 'options' => array( '...

Can I Fully Prevent SQL Injection By PDO Prepared Statement Without Bind_param?

Answer : You're doing it right. The bound parameters are the one declared in a "prepared statement" using ?. Then they are bound using execute() with their value as a parameter to be bound to the statement. The protection comes from using bound parameters, not from using prepared statement Means it is not enough just to use prepare() but keep all variables in the query like this: $sql = $db->prepare("SELECT * FROM employees WHERE name ='$name'"); $sql->execute(); $rows = $sql->fetchAll(); Someone who said that meant "although technically you are using a prepared statement, you aren't binding variables to it". So it makes the query vulnerable all the same. To be protected, you have to substitute all variables in the query with placeholders, and then bind them: $sql = $db->prepare("SELECT * FROM employees WHERE name = ?"); $sql->bindParam(1, $name); $sql->execute(); $rows = $sql->fetchAll();...

Apache Virtual Host Always Redirecting To /dashboard

Answer : Put this as the first line in C:\...\httpd-vhosts.conf (and restart the web server): NameVirtualHost *:80 So, it should look like this: NameVirtualHost *:80 <VirtualHost *:80> ServerName localhost DocumentRoot "C:/xampp/htdocs" </VirtualHost> <VirtualHost *:80> ServerName walkpeakdistrict.local DocumentRoot "C:/xampp/htdocs/walkpeakdistrict_uk/public" </VirtualHost> I would place all my projects somewhere outside of C:/xampp/htdocs and C:/xampp . Let C:/xampp/htdocs be the standard localhost location, with just two files inside (simple index.php and index.html ), but use another one for the projects. Even better, use another partition, not the system partition C: . Like D:/projects , or so. So, you would have D:/projects/walkpeakdistrict_uk . Good luck. Ok, I'm not sure why this was an issue but it seems to work when I change the virtual host's server name to anything other than ".loca...

Adding Days To $Date In PHP

Answer : All you have to do is use days instead of day like this: <?php $Date = "2010-09-17"; echo date('Y-m-d', strtotime($Date. ' + 1 days')); echo date('Y-m-d', strtotime($Date. ' + 2 days')); ?> And it outputs correctly: 2010-09-18 2010-09-19 If you're using PHP 5.3, you can use a DateTime object and its add method: $Date1 = '2010-09-17'; $date = new DateTime($Date1); $date->add(new DateInterval('P1D')); // P1D means a period of 1 day $Date2 = $date->format('Y-m-d'); Take a look at the DateInterval constructor manual page to see how to construct other periods to add to your date (2 days would be 'P2D' , 3 would be 'P3D' , and so on). Without PHP 5.3, you should be able to use strtotime the way you did it (I've tested it and it works in both 5.1.6 and 5.2.10): $Date1 = '2010-09-17'; $Date2 = date('Y-m-d', strtotime($Date1 . " + 1 day...

Can PHP CURL Retrieve Response Headers AND Body In A Single Request?

Answer : One solution to this was posted in the PHP documentation comments: http://www.php.net/manual/en/function.curl-exec.php#80442 Code example: $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 1); // ... $response = curl_exec($ch); // Then, after your curl_exec call: $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $header = substr($response, 0, $header_size); $body = substr($response, $header_size); Warning: As noted in the comments below, this may not be reliable when used with proxy servers or when handling certain types of redirects. @Geoffrey's answer may handle these more reliably. Many of the other solutions offered this thread are not doing this correctly. Splitting on \r\n\r\n is not reliable when CURLOPT_FOLLOWLOCATION is on or when the server responds with a 100 code. Not all servers are standards compliant and transmit just a \n for new lines. Detecting the size of the headers via CURLINFO_HEA...

Change Month Name To French

Answer : Use strftime : http://php.net/manual/en/function.strftime.php <?php setlocale(LC_TIME, "fr_FR"); echo strftime(" in French %d.%M.%Y and"); (not sure about that %d.%M.%Y but you can read documentation) From http://php.net/manual/en/function.date.php: To format dates in other languages, you should use the setlocale() and strftime() functions instead of date(). I know this is old but for anyone still looking this up, a more complete answer for your date in French would be: //set locale setlocale(LC_TIME, "fr_FR"); Then //echo date/formatting based on your locale, in this case, for French echo strftime("le %d %B, %Y", strtotime( $sgps_newsletter->getCreatedAt() )); //without day of the week = le 18 septembre, 2013 OR echo strftime("%A le %d %B, %Y", strtotime( $sgps_newsletter->getCreatedAt() )); //with day of the week = mercredi le 18 septembre, 2013 OR echo strftime("%d/%m/%Y", ...

Codeigniter Redirect -- The URI You Submitted Has Disallowed Characters

Answer : CodeIgniter checks all URI segments for disallowed characters. This happens by white listing allowed characters. Which ones are allowed can be checked in /system/application/config/config.php in the $config['permitted_uri_chars'] variable. permitted_uri_chars are the characters that CodeIgniter accepts in your URI.The default value is set to something like. $config['permitted_uri_chars'] = 'a-z 0-9~%.:&_\-'; By default only these are allowed: a-z 0-9~%.:_- Leave blank to allow all characters -- but only if you are insane. %22 comes for " .You can add this in permitted_uri_chars list. Try this may help but is not recommended , in your application/config/config.php change: $config['permitted_uri_chars'] = ''; #keep it blank to allow all characters $config['allow_get_array'] = TRUE; $config['enable_query_strings'] = TRUE;

Coalesce Function For PHP?

Answer : There is a new operator in php 5.3 which does this: ?: // A echo 'A' ?: 'B'; // B echo '' ?: 'B'; // B echo false ?: 'B'; // B echo null ?: 'B'; Source: http://www.php.net/ChangeLog-5.php#5.3.0 PHP 7 introduced a real coalesce operator: echo $_GET['doesNotExist'] ?? 'fallback'; // prints 'fallback' If the value before the ?? does not exists or is null the value after the ?? is taken. The improvement over the mentioned ?: operator is, that the ?? also handles undefined variables without throwing an E_NOTICE . First hit for "php coalesce" on google. function coalesce() { $args = func_get_args(); foreach ($args as $arg) { if (!empty($arg)) { return $arg; } } return NULL; } http://drupial.com/content/php-coalesce

Apache Server Ignores .htaccess

Answer : <Directory "/home/page_url/www/"> AllowOverride None This AllowOverride None disables .htaccess files from being read. See the manual. Also, please bear in mind that there's nothing magical about .htaccess files. They are a crude workaround for not having full access to the server configuration. All they are is a piece of Apache configuration. If you have full access to the server configuration, you should be putting stuff like this into the vhost configuration, not .htaccess files. As Jim said, if you have full access to your server, you should just put everything in the server configuration files. I reached here because I thought my server was ignoring my own htaccess/server configuration files. However, it turned out I had mod_expires and mod_rewrite disabled. After I had those two looked into, everything was working again as it should. You can enable them by executing these commands: sudo a2enmod expires sudo a2enmod rewrite ...

Are "elseif" And "else If" Completely Synonymous?

Answer : From the PHP manual: In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different (if you're familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior. Essentially, they will behave the same, but else if is technically equivalent to a nested structure like so: if (first_condition) { } else { if (second_condition) { } } The manual also notes: Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define your if/elseif conditions, you must not separate else if into two words, or PHP will fail with a parse error. Which means that in the normal control structure form (ie. using braces): if (first_condition) { } elseif (second_condition) { } either elseif or else ...

Apache Is Not Running From XAMPP Control Panel ( Error: Apache Shutdown Unexpectedly. This May Be Due To A Blocked Port)

Answer : There are many possible answers for this problem. The most common and most likely is that you're running another program which is blocking port 80 or 443. If you've installed Skype, then you've found your problem! Change apache's port settings to 81 and apache will work. There's a good tutorial on that To check this you can open up your command line by clicking the start menu, and typing 'cmd', and enter the command netstat -nab this wil return a list of programs that will vaguely resemble this pattern [someprogram.exe] UDP [fe80::numbers:numbers:numbers:numbers%numbers]:portnumber You need to find a line (or lines) ending in :80 and terminate them in order to start apache. If there is no line ending in :80, there are more things you can do. First, navigate to xampp's directory (default is c:\xampp) and double click apache_start.bat. This will open up a comand line and return more detailed errors about why apache can...

Any Way To Specify Optional Parameter Values In PHP?

Answer : PHP does not support named parameters for functions per se. However, there are some ways to get around this: Use an array as the only argument for the function. Then you can pull values from the array. This allows for using named arguments in the array. If you want to allow optional number of arguments depending on context, then you can use func_num_args and func_get_args rather than specifying the valid parameters in the function definition. Then based on number of arguments, string lengths, etc you can determine what to do. Pass a null value to any argument you don't want to specify. Not really getting around it, but it works. If you're working in an object context, then you can use the magic method __call() to handle these types of requests so that you can route to private methods based on what arguments have been passed. A variation on the array technique that allows for easier setting of default values: function foo($arguments) { $defaults = array( ...

Base Table Or View Not Found: 1146 Table Laravel 5

Answer : I'm guessing Laravel can't determine the plural form of the word you used for your table name. Just specify your table in the model as such: class Cotizacion extends Model{ public $table = "cotizacion"; Check your migration file, maybe you are using Schema::table, like this: Schema::table('table_name', function ($table) { // ... }); If you want to create a new table you must use Schema::create: Schema::create('table_name', function ($table) { // ... }); I faced this problem too in laravel 5.2 and if declaring the table name doesn't work,it is probably because you have some wrong declaration or mistake in validation code in Request (If you are using one)

CodeIgniter 4 Redirect Function Not Working

Answer : as per CI 4 use return redirect()->to('url'); if you are using route then use return redirect()->route('named_route'); In codeigniter 4 redirect()->to() returns a RedirectResponse object, which you need to return from your controller to do the redirect. for ex. class Home extends BaseController { public function index() { return redirect()->to('https://example.com'); } }

Catching Stripe Errors With Try/Catch PHP Method

Answer : If you're using the Stripe PHP libraries and they have been namespaced (such as when they're installed via Composer) you can catch all Stripe exceptions with: <?php try { // Use a Stripe PHP library method that may throw an exception.... \Stripe\Customer::create($args); } catch (\Stripe\Error\Base $e) { // Code to do something with the $e exception object when an error occurs echo($e->getMessage()); } catch (Exception $e) { // Catch any other non-Stripe exceptions } I think there is more than these exceptions ( Stripe_InvalidRequestError and Stripe_Error ) to catch. The code below is from Stripe's web site. Probably, these additional exceptions, which you didn't consider, occurs and your code fails sometimes . try { // Use Stripe's bindings... } catch(Stripe_CardError $e) { // Since it's a decline, Stripe_CardError will be caught $body = $e->getJsonBody(); $err = $body['error']; print('Status is:...

CodeIgniter : Unable To Load The Requested File:

Answer : try $this->load->view('home/home_view',$data); (and note the " ' " not the " ‘ " that you used) File names are case sensitive - please check your file name. it should be in same case in view folder I error occor. When you are trying to access a file which is not in the director. Carefully check path in the view $this->load->view('path'); default root path of view function is application/view . I had the same error. I was trying to access files like this $this->load->view('pages/view/file.php'); Actually I have the class Pages and function. I built the function with one argument to call the any files from the director application/view/pages . I was put the wrong path. The above path pages/view/files can be used when you are trying to access the controller. Not for the view. MVC gave a lot confusion. I had this problem. I just solve it. Thanks.

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Answer : if anyone pass through here, this is shorter solution: sudo chown -R $USER $HOME/.composer it seems to me the group information is missing in your command sudo chown -R <user> /home/<user>/.composer/cache/repo/https---packagist.org Shoud be sudo chown -R <user>:<group> /home/<user>/.composer/cache/repo/https---packagist.org But to avoid other permission issues, I would rather advise: sudo chown -R <user>:<group> /home/<user>/.composer/cache (you'll need access to other folders in there) and sudo chown <user>:<group> /home/<user>/.composer To make sure your user has permissions enough on the global composer folder. Mind the missing recursion so the user don't own keys created by root. If you need to find out the group: groups <user>