Labels

Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Thursday, 25 April 2019

Uploading multiple files/array of files through curl in php

Many might have run in to issues while trying to upload multiple files or sending multipart form data to server through curl . Ideally, to send multiple files, one would save the files to an array variable and pass it through curl. But this would end up in error "Array to string conversion in /path/to/upload.php"

This means you are trying to send the files as mentioned in the below code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php

$user = "admin";

$postField = array();

$postFields['user'] = $user; //postdata

$postFields['upload_file'] = array(

        'file[0]' => '@' . realpath('first-file.jpg'),
        'file[1]' => '@' . realpath('second-file.jpg')
    )

$headers = array("Content-Type" => "multipart/form-data");
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, "http://serverdomain.com/upload/uploadMultipleFiles");
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_handle, CURLOPT_POST, TRUE);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, TRUE);

$returned_data = curl_exec($curl_handle);
curl_close($curl_handle);
echo $returned_data ;
?> 


This is what should be the ideal code to send multiple files through php as per the manual, but pragmatically, it isn't right. You will not be able to send array of files through curl or technically, we can say, it won't support multi-dimensional arrays. Instead, you can send them as multiple CURL File objects
(PHP 5 >= 5.5.0, PHP 7) or single dimension array if you are using PHP <5. 

So the below code would help you send multiple files using CURL File object:




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php

$user = "admin";

$postField = array();

$postFields['user'] = $user; //postdata

$postFields['upload_file_0'] = curl_file_create(
     realpath('first-file.jpg'), "mime", 'first-file.jpg' );

$postFields['upload_file_1'] = curl_file_create( 
     realpath('second-file.jpg'), "mime", 'second-file.jpg' );

$headers = array("Content-Type" => "multipart/form-data");
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, "http://serverdomain.com/upload/uploadMultipleFiles");
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_handle, CURLOPT_POST, TRUE);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, TRUE);

$returned_data = curl_exec($curl_handle);
curl_close($curl_handle);
echo $returned_data ;
?>



If your version of php doesn't support CURL File objects, you can declare the array as

$postFields['upload_file_0'] = '@' . realpath('first-file.jpg');//@ is mandatory to send files

$postFields['upload_file_1'] = '@' . realpath('first-file.jpg');

In case of more than two files or some 'n' number of files you can use loop:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php

$user = "admin";
$fileName = array();
$tempFileName = array();

 

$filecount = count($_FILES['upload_file']['name']);
for($i=0; $i<$filecount; $i++){
$fileName[] = $_FILES["upload_file"]['name'][$i];
$tempFileName[] = $_FILES["upload_file"]['tmp_name'][$i];
} 

 $postField = array();

$postFields['user'] = $user; //postdata

foreach ($tempFileName as $index => $file) {
  if (function_exists('curl_file_create')) { // For PHP 5.5+
    $file = curl_file_create($file, "mime", $fileName[$index]);
  } else {
    $file = '@' . realpath($file);
  }
  $postFields["upload_file_$index"] = $file;
}

$headers = array("Content-Type" => "multipart/form-data");
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL,  
"http://serverdomain.com/upload/uploadMultipleFiles");
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_handle, CURLOPT_POST, TRUE);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, TRUE);

$returned_data = curl_exec($curl_handle);
curl_close($curl_handle);
echo $returned_data ;
?> 


Hope this helped you dig out a perfect solution!

Wednesday, 20 March 2019

Migrating your wordpress from localhost to server or from one domain to other domain


Migrating your wordpress from localhost to server

To move the wordpress site from one host to the other host or server, you can directly make the changes in the MySQL database itself.
Login to your phpmyadmin or MySQL command line and use the following commands on your wordpress database:

1. 
  UPDATE wp_options
     SET option_value = 'http://new_domain_name.com'
     WHERE option_name = 'home';
2.
 UPDATE wp_options
    SET option_value = 'http://new_domain_name.com'
    WHERE option_name = 'siteurl';
3.
UPDATE wp_posts
    SET post_content = REPLACE(post_content,
    'http://old_domain_name.com', 'http://new_domain_name.com');
4.
UPDATE wp_posts
    SET guid = REPLACE(guid,'http://old_domain_name.com', 
     'http://new_domain_name.com');


To make sure there are no broken links, reset your permalinks by following the below steps:
  1. Log in to your WordPress admin panel.
  2. Click Settings.
  3. From the Settings menu, click Permalinks.
  4. Note which kind of Permalink you currently use.(for custom permalink, copy the current permalink structure and save it in a notepad for later use)
  5. Select any Permalink setting other than the one you currently use, and then click Save Changes.
  6. Select your original Permalink setting(paste the above copied permalink structure in custom permalink), and then click Save Changes.

Wednesday, 29 August 2018

Pagination in PHP, MYSQL serverside API

Pagination is a useful concept when there is a requirement of retreiving large chunks of data from server. Pagination reduces the load on server and also is user friendly as the end user sees less data in a go.

So here I am using PHP to retreive rows from MYSQL using pagination.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#retreive start and limit values 
if(isset($_POST["start"])) {
        $start = $_POST["start"]-1;
} else {
        $start = 0;
}

##number of rows to be retreived from starting point, can be 10,20,30...
if(isset($_POST["limit"])) {
        $limit = $_POST["limit"] ;
} else {
        $limit = 10 ; //get 10 as default from starting point
}

#set header
header('Content-Type: application/json');

#connection to database
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);

#form query
$sql = "Select * from mytable LIMIT $start, $limit ";     ##this query retreives rows from mytable starting from start point and upto $limit rows

#execute query
$retval = mysqli_query( $conn, $sql );

#fetch rows if query executed succesfully else return error
if(! $retval ) {
        $data = array("status"=>"failure","message"=>"Log fetch error!!");
        echo json_encode( $data );
        mysqli_close($conn);
        die('Could not fetch logs: ' . mysqli_error());
}
else {
        while($row = mysqli_fetch_array($retval, MYSQL_ASSOC)) {
              $data[] = $row;
        }

##send response to client
                $data = array('status'=>'success','message'=>'Log fetched.','records'=>$data);

#close connection
        mysqli_close($conn);
        echo json_encode( $data );
}

This script will fetch rows from database based on start and limit variables. If these variables are not passed during client request it sets to default of 0 to 10 rows.

Happy Coding.

Friday, 24 August 2018

Saving unicode or utf8 data using PHP-MYSQL

Saving data in MYSQL is almost common in every website. When it comes to unicode date there is a bit of overhead that needs to be taken care of. I am listing those settings step by step.

1. Set table's collation to "utf8_general_ci"

 

 ALTER TABLE <table_name> CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;  

 

2. Set the column's collation to "utf8_general_ci"

 

 ALTER TABLE <table_name> MODIFY <column_name> VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci;

3. In PHP use the below code while the data is being inserted into the table.


 mysqli_query($conn,"SET names 'utf8'");

Monday, 27 November 2017

Make a list element active when included using php include


Often there is a requirement to make a menu element active when we import something using php include. Its quite simple and this is how its done.

<? php include "includes/sidebar.php"; ?>   

(sidebar.php): 

<ul id="sidebar">
  <li><a href="link1.html">Link1</a></li>
  <li><a href="link2.html">Link2</a></li>
  <li><a href="link3.html">Link3</a></li>
  <li><a href="link4.html">Link4</a></li>
</ul>

CSS:

ul#sidebar > li.active {
 background-color:#6495ED;
 color:#fff;
}

Javascript (jQUery solutuion): 


//current url being access
 var cur_href = window.location.href;
 $(document).ready(function(){
  $("#sidebar li a").each(function(){
   //get current href link
   var cur_attr =$(this).attr('href');  
   //save into regex
   var regex = new RegExp(cur_attr,"ig");
   //test if current link and current href matched
   if(regex.test(cur_href)) {
    $(this).parent().addClass('active'); //if yes then addClass 'active'
   } else {
    $(this).parent().removeClass('active'); //else removeClass 'active'
   }
  });
 });

This will make current menu link active in sidebar.

Monday, 6 November 2017

Handling error "You probably tried to upload a file that is too large. Please refer to documentation for a workaround for this limit."


Handling error "You probably tried to upload a file that is too large. Please refer to documentation for a workaround for this limit."

Usually, we come across such errors when we try to import a large file in to mysql through phpmyadmin. This is because there is a pre-defined file limit in php for file upload which is 2MB.

You may change the file upload limit as per your requirement by changing php configuration following the below steps :

1. Navigate to apache2 directory and open php.ini file using vi or vim editor.


root@user-B85M-D3H:~# vim /etc/php5/apache2/php.ini 

2. Change the values of the following lines to as per your requirement.(I am changing the limit to 120 MB here)

&nbsp;upload_max_filesize 120M //file size
&nbsp;post_max_size 120M
&nbsp;max_execution_time 200
&nbsp;max_input_time 200

3. Please ensure that the max_execution_time, max_input_time should always be greater than upload_max_filesize and post_max_size.

4. Once you make the changes, save the file and restart the apache server using the command :

service apache2 restart  

Hope this helps. Happy coding!