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


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.


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


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.

			A Web Interface

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

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

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

					<button id="submit" type="button" class="btn btn-default navbar-btn" onclick="submittext();">
					<img style="margin-left:2%;height:4%;position:relative;" id="loading" src="images/processing.gif"></img>
			<textarea id="input"></textarea> 
			<textarea id="result"></textarea> 
					<button id="edit" type="button" class="btn btn-default navbar-btn" onclick="edittext();">
					<button id="sample1" type="button" class="btn btn-default navbar-btn sample" onclick="sample(this.id);">
					<button id="sample2" type="button" class="btn btn-default navbar-btn sample" onclick="sample(this.id);">
					<button id="sample3" type="button" class="btn btn-default navbar-btn sample" onclick="sample(this.id)">
					<button id="clear" type="button" class="btn btn-default navbar-btn" onclick="empty();">
					<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>

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

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


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

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

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(){

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

	//Ajax call to upload and submit for conversion
		type: 'POST',
		url: "scripts/convert.php",
		//data: "&from=" + from + "&to=" + to + "&text=" + srctext,
		data: "&text=" + srctext,
		success: function (data) {
			var tgttext = data;
			$('#download').prop('disabled', false);
			$('#language').prop('disabled', false);
		error:function  (jqXHR, exception) {
			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.

$text = $_POST["text"];

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

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

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

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


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

$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);
//echo 'Operation completed without any errors';
// Close handle

#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

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!