Category: php

How to test PHP installation

To test a successful php installation. We can check the PHP version in your machine or test the entire PHP setup using following

open a file in which your web directory name it anything like php_test.php and write the following content.

?php
phpinfo();
?>

Save the file and open the file in your browser like localhost/php_test.php.

Then you will notice that if php is installed the following image will be displayed.

PHP successful installation screenshot

There is a video tutorial that explains the same as above.

How to debug your code in PHP and most common mistakes in PHP.

Here we will see some tips and most common problems that programmers generally encounter while writing PHP code.

Common errors or mistakes and debugging tips

  • First and foremost thing is check your error.log file. For Ubuntu it is at /var/log/apache2/error.log or most Linux distribution this file is at /var/log/htttp/error.log.
  • Open a terminal and type tail -f /var/log/apache2/error.log. This command will open the file and in be in waiting mode and it will update as any changes are made it writes to the standard output. After running this command just type enter button for 2 or 3 times so that you can cleary distinguish between previous errors and new errors. Of course you can distinguish with the timestamp from the log too. Now just execute the PHP code and see the errors in the terminal. You may have a look at this image.
  • Now even after seeing the log you may have found some errors and fixed them. But still your code might not be doing what you want it to do. So now look for logical errors that you might have done. To find this errors write print/echo statement at crucial points and see if the variable is storing the value is as expected.
  • Another most common error the permission denied error when dealing with files. To solve this you can give your files that are throwing this error the www-root:www-root permission if you are on Ubuntu or apache:apache in other Linux distributions. This can be done using chown command. For example chown www-data:www-data file.txt.
  • If you are using Mysql to connect to database and a query is not executing using the variables it is receiving print that query just before it executes and then try the same query in your mysql command line interface and see if if fetches the desired result or throws any error.

These are the common tips and errors that I encounter and I had given tips from my experience. I will update this list as I do more. Thank you.

Linking a Python script to a web interface with file upload.

In this article I am going to explain how can we link a python script with a web interface. In case you need the GIT hub link for the entire project you can find it here.

Requirements:

  • PHP
  • Web Server(apache)
  • Javascript
  • A Python script that you want to link with the web interface.

The Python Script

#convert text to lowercase 

import sys
#open file using open file mode
fp1 = open(sys.argv[1]) # Open file on read mode -- input file
lines = fp1.read().split("\n") # Create a list containing all lines
fp1.close() # Close file

#write output to a file name it out.txt
fp2 = open("out.txt", "w")

#do something with the text and write it to the file
for line in lines:
	out_line = line.lower()
	fp2.write(out_line + "\n")


fp2.close()

This is our Python script that we want to use it from a Wen Interface where we give input text and the lower case text is shown in the web page itself. Remember I am here just taking a very small example this python script could be doing anything but the basic point is that it takes an input file with some text and writes the output to another file.

To make sure this works, run this python script independently and see if it works as expected.

python3 case_convert.py in.txt
  • Replace your python script with your code.
  • If you have any other script like in PERL, Shell script even then it works fine. You just need to change it in PHP script where it calls the system command.

This script takes a input file in.txt that contains some text and it will be converted to lower case when we execute the script and save it to a output file out.txt

Now lets build our Web page we will call it as index.html It will look like below.

<html>
	<head>
		<title>
			A Web Interface
		</title>

		<script src="js/jquery.js"></script>
		<script src="js/jquery-ui.js"></script>
		<script type="text/javascript" src="config.js"></script>
		<script type="text/javascript" src="js/FileSaver.js"></script>
		<script type="text/javascript" src="js/validation.js"></script>

		<link rel="stylesheet" type="text/css" href="bootstrap-3.3.5-dist/css/bootstrap.css" />
		<link rel="stylesheet" type="text/css" href="css/styles.css" />
		<link rel="stylesheet" type="text/css" href="css/responsive.css" />

		<script type="text/javascript" src="bootstrap-3.3.5-dist/js/bootstrap.js" ></script>
		<script type="text/javascript" src="js/convert.js" ></script>

		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
		 <meta charset='utf-8'>
	</head>
	<body>
		<div>

				<h4 align="center">Convert Upper case to LowerCase </h4>
			<!--common for file and text output-->
			<!--upload form-->
			<form class="form-inline" id="upload" method="post" enctype="multipart/form-data">

				<div class="form-group col-12 col-m-12">
					
					<label class="btn btn-primary" for="my-file-selector">

						<!--<input accept=".doc,.rtf,.docx,.pdf,text/plain" type="file" id="file" name="inputfile" multiple/>-->
						<input accept=".pdf,text/plain,.doc" type="file" id="file" name="inputfile" onchange="startRead(this)" multiple  multiple/>
					</label>

					<!--<button type="button" class="form-control btn btn-default dropdown-toggle" data-toggle="dropdown">
						Select Business type <span class="caret"></span>
					</button>-->
				<!--	<span id="mandatory">*</span> <select name="srclanguage"  id="srclanguage" class="form-control"><option value="" >Choose Type</option>
						<option disabled="true"></option>
				</select>-->

					<button id="submit" type="button" class="btn btn-default navbar-btn" onclick="submittext();">
						Submit
					</button>
					<img style="margin-left:2%;height:4%;position:relative;" id="loading" src="images/processing.gif"></img>
					<br>
			<textarea id="input"></textarea> 
			<textarea id="result"></textarea> 
					<button id="edit" type="button" class="btn btn-default navbar-btn" onclick="edittext();">
						Edit
					</button>
					<br>
					<button id="sample1" type="button" class="btn btn-default navbar-btn sample" onclick="sample(this.id);">
						Sample1
					</button>
					<button id="sample2" type="button" class="btn btn-default navbar-btn sample" onclick="sample(this.id);">
						Sample2
					</button>
					<button id="sample3" type="button" class="btn btn-default navbar-btn sample" onclick="sample(this.id)">
						Sample3
					</button>
					<button id="clear" type="button" class="btn btn-default navbar-btn" onclick="empty();">
						clear
					</button>
					<select style="background-color:#7ba733;color:#fff;" name="savetype"  id="savetype" class="form-control"><option value="" >Export to</option>
						<option disabled="true"></option>
						<option value="txt">.txt </option>
						<option value="csv">.csv </option>
						<option value="doc">.doc</option>
						<option value="rtf">.rtf</option>
						<option value="pdf">.pdf</option>
					</select>

					<button id="download" type="button" disabled class="btn btn-default navbar-btn" onclick="saveasfile();">
						Download
					</button>

				</div> <!-- end of form group div -->

			</form>


			<div class="progressbar">
				<div class="bar">
				</div>

			</div> <!-- end of progressbar div-->

			<!--<div contenteditable="true" id="result"></div>--> <!-- end of result div-->
			<!--			<textarea onkeypress="txtAreaId(this.id);" id="result-text"></textarea> -->

		</div>	<!-- end of container div -->
	</body>
</html>

Looks like a lot but it simply does hold two textareas, button for submitting input text, downloading the output text and linked Javascript and CSS files.

The main Javascript file convert.js which is in js folder will call a PHP script that will execute our python program. I will just list the main function here that is activated when we click submit after inputting some text.

//called when submit button button is clicked
function submittext(){
	$("#savetype").hide();
	$("#download").hide();
	//$("#result").hide();

	//retrieve values from fields
	var srctext = $("#input").val();
	//alert(fromto+" "+srctext);
	
	
	if(typeof srctext =="undefined" || srctext =="") {
		alert("Provide some text...");
		return false;
	}


	$("#loading").show();
	$("#result").empty();
	//Ajax call to upload and submit for conversion
	$.ajax({
		type: 'POST',
		url: "scripts/convert.php",
		//data: "&from=" + from + "&to=" + to + "&text=" + srctext,
		data: "&text=" + srctext,
		header:"application/x-www-form-urlencoded",
		async:false,
		success: function (data) {
			$("#loading").hide();
			//alert(data);
			var tgttext = data;
			$("#result").val(tgttext);
			$('#download').prop('disabled', false);
			$('#language').prop('disabled', false);
			$("#savetype").show();
			$("#download").show();
			$("#edit").show();
		
		},
		error:function  (jqXHR, exception) {
			$("#loading").hide();
			var msg = '';
			if (jqXHR.status === 0) {
				msg = 'Not connect.\n Verify Network.';
			} else if (jqXHR.status == 404) {
				msg = 'Requested page not found. [404]';
			} else if (jqXHR.status == 500) {
				msg = 'Internal Server Error [500].';
			} else if (exception === 'parsererror') {
				msg = 'Requested JSON parse failed.';
			} else if (exception === 'timeout') {
				msg = 'Time out error.';
			} else if (exception === 'abort') {
				msg = 'Ajax request aborted.';
			} else {
				msg = 'Uncaught Error.\n' + jqXHR.responseText;
			}
			alert(msg+" Please try afer sometime");
		}
	});
	return false;
}

So we can see that we are using AJAX which explains why we need jQuery. In the AJax look at the URL it is calling a PHP script convert.php located in scripts directory.

convert.php will look like below. I recommend PHP 7 although it works in lower versions too.

<?php
$text = $_POST["text"];

$fp = fopen("in.txt","w");
fwrite($fp,$text);
fclose($fp);

#call your python script here and make sure your python script is also at same place as this script
$status = system("python3 case_convert.py in.txt");

$fp_out = fopen("out.txt","r");
if ($fp_out) {
    while (($line = fgets($fp_out)) !== false) {
        // process the line read.
        echo "$line";
    }

    fclose($fp_out);
} else {
    // error opening the file.
}

?>

After doing all these. You need to give proper permission the scripts directory or just the two files in.txt and out.txt. Below is the command to do the same.

chown www-data:www-data scripts 
chown www-data:www-data in.txt out.txt

After doing this load your web page in the browser. For example I named the directory as basic-web-interface, so in my browser I open it as http://localhost/basic-web-interface/.

If you have PHP/ APACHE and all other javascript and Bootstrap files installed it should load your web page without any hiccups.

Then provide some input text and see that it gets convert to lowercase and the output text is displayed in the other textarea.

Debugging
  • Check apache error..log file for errors. For ubuntu it is /var/log/apache2/error.log
  • Open Network console(F12) from Browser Developer options and view the API request that is being called. Its request, response, parameters etc.
  • For this Open Developer options, click on network tab and then click submit and view the request/reponse.

PHP calling a POST request API using CURL

In this article we will see how can we call a post request using CURL. This curl request can send post data/json post data, disable SSL verification of host(when you call https), also you can send a Authorization Bearer token a secret shared by your API host.

Pre-Requisites: Install php-curl. Choose the below command according to your PHP Version.

sudo apt install php5-curl 
sudo apt install php7.0-curl

Now lets suppose we are having an API call that just does some function with the string you pass to it.

Now lets write the code.

<?php

#get the required variables
$slang = 'eng';
$tlang = 'hin';
$str = "Hello. How are you?";
#$token = 'LongsecretstringsharedbyyourAPIhost"

#parameters
$data = array("source_language"=>$slang, "target_language"=>$tlang, "text"=>$str);

#set the header type if you want to send json response
header('content-type: application/json');

#calling api here, replace with your URL
$ch = curl_init("http://getAPI/request/");
curl_setopt($ch, CURLOPT_POST, true);

#comment below line if you are not sending data as JSON
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_PROXY, '');

#set  headers, remove authorization if you are not using one
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer '.$token));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

#comment below line if you don't want to SSL Verification to false
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

#execute the curl request 
if(curl_exec($ch) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
else
{
//echo 'Operation completed without any errors';
}
// Close handle
curl_close($ch);

#send response
echo $response;

With the above code you can call any API you want to and configure the CURL request as per your requirements.

Set up PHP mailer on Go Daddy

Popular hosting provider GoDaddy imposes very strict (to the point of becoming almost useless) constraints on sending an email. They block outbound SMTP to ports 25, 465 and 587 to all servers except their own.

If you find your script works on your local machine, but not when you upload it to GoDaddy, then you’ll have to refrain from using SMTP attributes in your PHP mail script. Instead, you can simply use Go Daddy’s web mailer to configure PHP mailer and provide the host name, username and password to enable sending  mails on your script. Use the following code after configuring your webmailer:

$mail = new PHPMailer;

$mail->Host = 'localhost';              // Specify this option as localhost
$mail->Username = 'info@yourdomain.com';// webmailer username
$mail->Password = 'your pwd';           // webmailer password
$mail->Port = 587;                      // TCP port to connect to

  
$mail->setFrom('your from mail address', 'From name');

$mail->addAddress(recipientemail);      // Add a recipient in $email

PS : You might get following errors while trying to run PHP mailer with SMTP on Go Daddy :

Error : PHPMailer- Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

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:

<?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:

<?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:

<?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!

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.

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.

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

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'");

Make a list menu 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 solution):

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