Posts

Showing posts with the label Php

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( '...

Alternative For Define Array Php

Answer : From php.net... The value of the constant; only scalar and null values are allowed . Scalar values are integer, float, string or boolean values. It is possible to define resource constants, however it is not recommended and may cause unpredictable behavior. But You can do with some tricks : define('names', serialize(array('John', 'James' ...))); & You have to use unserialize() the constant value (names) when used. This isn't really that useful & so just define multiple constants instead: define('NAME1', 'John'); define('NAME2', 'James'); .. And print like this: echo constant('NAME'.$digit); This has changed in newer versions of PHP, as stated in the PHP manual From PHP 5.6 onwards, it is possible to define a constant as a scalar expression, and it is also possible to define an array constant .

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...

Composer Install Error - Requires Ext_curl When It's Actually Enabled

Answer : This is caused because you don't have a library php5-curl installed in your system, On Ubuntu its just simple run the line code below, in your case on Xamp take a look in Xamp documentation sudo apt-get install php5-curl For anyone who uses php7.0 sudo apt-get install php7.0-curl For those who uses php7.1 sudo apt-get install php7.1-curl For those who use php7.2 sudo apt-get install php7.2-curl For those who use php7.3 sudo apt-get install php7.3-curl For those who use php7.4 sudo apt-get install php7.4-curl Or simply run below command to install by your version: sudo apt-get install php-curl This worked for me: http://ubuntuforums.org/showthread.php?t=1519176 After installing composer using the command curl -sS https://getcomposer.org/installer | php just run a sudo apt-get update then reinstall curl with sudo apt-get install php5-curl . Then composer's installation process should work so you can finally run php composer.phar install to get the dependencies list...

Convert Command Line CURL To PHP CURL

Answer : a starting point: <?php $pageurl = "http://hostname/@api/deki/pages/=TestPage/files/="; $filename = "test.png"; $theurl = $pageurl . $filename; $ch = curl_init($theurl); curl_setopt($ch, CURLOPT_COOKIE, ...); // -b curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); // -X curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE); // --data-binary curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: image/png']); // -H curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); // -0 ... ?> See also: http://www.php.net/manual/en/function.curl-setopt.php You need ... curl-to-PHP : https://incarnate.github.io/curl-to-php/ "Instantly convert curl commands to PHP code" Whicvhever cURL you have in command line, you can convert it to PHP with this tool: https://incarnate.github.io/curl-to-php/ It helped me after long long hours of searching for a solution! Hope it will help you out too! Your solution is this: // Generated by curl-to-PHP: htt...

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...

A __construct On An Eloquent Laravel Model

Answer : You need to change your constructor to: public function __construct(array $attributes = array()) { parent::__construct($attributes); $this->directory = $this->setDirectory(); } The first line ( parent::__construct() ) will run the Eloquent Model 's own construct method before your code runs, which will set up all the attributes for you. Also the change to the constructor's method signature is to continue supporting the usage that Laravel expects: $model = new Post(['id' => 5, 'title' => 'My Post']); The rule of thumb really is to always remember, when extending a class, to check that you're not overriding an existing method so that it no longer runs (this is especially important with the magic __construct , __get , etc. methods). You can check the source of the original file to see if it includes the method you're defining.

Convert English Numbers To Arabic Numerals

Answer : If you are referring to what Wikipedia calls eastern arabic / indic numerals, a simple replace operation should do. $western_arabic = array('0','1','2','3','4','5','6','7','8','9'); $eastern_arabic = array('٠','١','٢','٣','٤','٥','٦','٧','٨','٩'); $str = str_replace($western_arabic, $eastern_arabic, $str); Definitions Western arabic numerals: "1234567890". Eastern arabic numerals: "١٢٣٤٥٦٧٨٩٠". The answer I wrote a couple of functions (gist.github.com) a while back. Demo (3v4l.org) echo arabic_w2e("1234567890"); // Outputs: ١٢٣٤٥٦٧٨٩٠ echo arabic_e2w("١٢٣٤٥٦٧٨٩٠"); // Outputs: 1234567890 Code <?php /** * Converts numbers in string from western to eastern Arabic numerals. * * @param string $str Arbitrary text * @return string Text with western Arabic numerals co...

Can PNG Image Transparency Be Preserved When Using PHP's GDlib Imagecopyresampled?

Answer : imagealphablending( $targetImage, false ); imagesavealpha( $targetImage, true ); did it for me. Thanks ceejayoz. note, the target image needs the alpha settings, not the source image. Edit: full replacement code. See also answers below and their comments. This is not guaranteed to be be perfect in any way, but did achieve my needs at the time. $uploadTempFile = $myField[ 'tmp_name' ] list( $uploadWidth, $uploadHeight, $uploadType ) = getimagesize( $uploadTempFile ); $srcImage = imagecreatefrompng( $uploadTempFile ); $targetImage = imagecreatetruecolor( 128, 128 ); imagealphablending( $targetImage, false ); imagesavealpha( $targetImage, true ); imagecopyresampled( $targetImage, $srcImage, 0, 0, 0, 0, 128, 128, $uploadWidth, $uploadHeight ); imagepng( $targetImage, 'out.png', 9 ); Why do you make things so complicated? the following is what I use and so far...

Converting HTML To Plain Text In PHP For E-mail

Answer : Use html2text (example HTML to text), licensed under the Eclipse Public License. It uses PHP's DOM methods to load from HTML, and then iterates over the resulting DOM to extract plain text. Usage: // when installed using the Composer package $text = Html2Text\Html2Text::convert($html); // usage when installed using html2text.php require('html2text.php'); $text = convert_html_to_text($html); Although incomplete, it is open source and contributions are welcome. Issues with other conversion scripts: Since html2text (GPL) is not EPL-compatible. lkessler's link (attribution) is incompatible with most open source licenses. here is another solution: $cleaner_input = strip_tags($text); For other variations of sanitization functions, see: https://github.com/ttodua/useful-php-scripts/blob/master/filter-php-variable-sanitize.php Converting from HTML to text using a DOMDocument is a viable solution. Consider HTML2Text, which requires PHP5: http://www.howtocreate.co.uk/p...

Can I Use Array_push On A SESSION Array In Php?

Answer : Yes, you can. But First argument should be an array. So, you must do it this way $_SESSION['names'] = array(); array_push($_SESSION['names'],$name); Personally I never use array_push as I see no sense in this function. And I just use $_SESSION['names'][] = $name; Try with if (!isset($_SESSION['names'])) { $_SESSION['names'] = array(); } array_push($_SESSION['names'],$name);

Call To Undefined Function Imagecreatefromjpeg() And GD Enabled

Image
Answer : I think you've installed an incomplete version of gd . When you compile the gd extension, use the flag --with-jpeg-dir=DIR and --with-freetype-dir=DIR ps. dont forget make clean picture below is the incomplete version of gd: picture below is the complete version of gd: In my case, GD was missing after upgrading to PHP 7.3. So, I just added it by using the following command : sudo apt-get install php7.3-gd

Composer Update Laravel

Answer : When you run composer update , composer generates a file called composer.lock which lists all your packages and the currently installed versions. This allows you to later run composer install , which will install the packages listed in that file, recreating the environment that you were last using. It appears from your log that some of the versions of packages that are listed in your composer.lock file are no longer available. Thus, when you run composer install , it complains and fails. This is usually no big deal - just run composer update and it will attempt to build a set of packages that work together and write a new composer.lock file. However, you're running into a different problem. It appears that, in your composer.json file, the original developer has added some pre- or post- update actions that are failing, specifically a php artisan migrate command. This can be avoided by running the following: composer update --no-scripts This will run the compos...

Convert Float To String In Php?

Answer : echo number_format($float,0,'.',''); note: this is for integers, increase 0 for extra fractional digits $float = 0.123; $string = sprintf("%.3f", $float); // $string = "0.123"; It turns out json_decode by default casts large integers as floats. This option can be overwritten in the function call: $json_array = json_decode($json_string, , , 1); I'm basing this only on the main documentation, so please test and let me know if it works.

"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>

Connect PHP To MSSQL Via PDO ODBC

Answer : There are several configuration files you need to have set up. /etc/odbc.ini , /etc/odbcinst.ini and /etc/freetds/freetds.conf (these locations are valid for Ubuntu 12.04 and probably correct for most *nixes). You'll need to install unixodbc and freetds (not sure what the package names are on CentOS). In Ubuntu this would be apt-get install unixodbc tdsodbc . For help installing these, look at this question Can't Install FreeTDS via Yum Package Manager /etc/odbc.ini (this file may be empty) # Define a connection to a Microsoft SQL server # The Description can be whatever we want it to be. # The Driver value must match what we have defined in /etc/odbcinst.ini # The Database name must be the name of the database this connection will connect to. # The ServerName is the name we defined in /etc/freetds/freetds.conf # The TDS_Version should match what we defined in /etc/freetds/freetds.conf [mssql] Description = MSSQL Server Driver = free...

Ajax Add To Cart Button For Product Variation In WooCommerce 3

Answer : To make it work I use a custom ajax add-to-cart for product variations exclusively. 1). I have first changed a bit your button html: <div class="btnss"> <span class="price"> <span class="woocommerce-Price-amount amount">6,999&nbsp; <span class="woocommerce-Price-currencySymbol">kr</span> </span> </span> <div class="quantity buttons_added"> <input type="button" value="-" class="minus"> <label class="screen-reader-text" for="quantity_5b101f605f067">Quantity</label> <input type="number" id="quantity_5b101f605f067" class="input-text qty text" step="1" min="1" max="" name="quantity" value="1" title="Qty" size="4" pattern="[0-9]*" inputm...

ABSPATH Or __FILE__?

Answer : I would personally prefer dirname() as it is always guaranteed to give me the correct result, while the ABSPATH method relies on a fixed theme path and theme name that can both change. By the way, you can use __DIR__ instead of dirname(__FILE__) . The path to the "wp-content" directory and its subdirectories can be different in a particular WordPress installation. Also, using the WordPress internal constants (such as ABSPATH ) is not recommended. See the Determining Plugin and Content Directories WordPress Codex article. Since PHP 4.0.2, symlinks are being resolved for the __FILE__ and __DIR__ magic constants, so take that into account. Bottom line : To determine the absolute path to a theme directory, I would suggest to use the get_template_directory() function which also applies filters and internally combines get_theme_root() and get_template() . For my own projects I would choose dirname(__FILE__) , also there is a new constant in PHP: __DIR__...

Bulk Insertion In Laravel Using Eloquent ORM

Answer : You can just use Eloquent::insert() . For example: $data = array( array('name'=>'Coder 1', 'rep'=>'4096'), array('name'=>'Coder 2', 'rep'=>'2048'), //... ); Coder::insert($data); We can update GTF answer to update timestamps easily $data = array( array( 'name'=>'Coder 1', 'rep'=>'4096', 'created_at'=>date('Y-m-d H:i:s'), 'modified_at'=> date('Y-m-d H:i:s') ), array( 'name'=>'Coder 2', 'rep'=>'2048', 'created_at'=>date('Y-m-d H:i:s'), 'modified_at'=> date('Y-m-d H:i:s') ), //... ); Coder::insert($data); Update: to simplify the date we can use carbon as @Pedro Moreira suggested $now = Carbon::now('utc')->toDateTimeString(); $data = array( ...

Convert Tiff To Jpg In Php?

Answer : In the forum at http://www.php.net/gd the following comment is written: IE doesn't show TIFF files and standard PHP distribution doesn't support converting to/from TIFF. ImageMagick (http://www.imagemagick.org/script/index.php) is a free software that can read, convert and write images in a large variety of formats. For Windows users it includes a PHP extension php_magickwand_st.dll (and yes, it runs under PHP 5.0.4). When converting from TIFF to JPEG, you must also convert from CMYK color space to RGB color space as IE can't show CMYK JPGs either. Please note: -TIFF files may have RGB or CMYK color space -JPEG files may have RGB or CMYK color space Here are example functions using ImageMagick extension: - convert TIFF to JPEG file formats - convert CMIK to RGB color space - set image resolution to 300 DPIs (doesn't change image size in pixels) <?php function cmyk2rgb($file) { $mgck_wnd = NewMagickWand(); MagickReadImage($mgck_wnd, $file); $im...