#!/usr/bin/python
#A function is created with the def keyword
def function():
pass
#-------------------------------------------------------
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
#-------------------------------------------------------
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
print ("Values inside the function before change: ", mylist)
mylist[2]=50
print ("Values inside the function after change: ", mylist)
return
# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
#-------------------------------------------------------
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function
printinfo( age=50, name="miki" )
#-------------------------------------------------------
print "1 + 1 =", 1 + 1
print "2 * (2 + 3) =", 2 * (2+3)
print "1.2 / 0.3 =", 1.2 / 0.3
print "5 / 2 =", 5 / 2
# 1 + 1 = 2
# 2 * (2 + 3) = 10
# 1.2 / 0.3 = 4.0
# 5 / 2 = 2
#functions
def square(number):
sqr_num = number **2
return sqr_num
input_num = 5
output_num = square(input_num)
print "print output", output_num
#function morethan one input
def returnDifference(n1, n2):
"""Return the difference between two numbers.
Subtracts n2 from n1."""
return n1 - n2
print "print output", returnDifference(1,1)
def add_two_numbers(num1, num2):
sum = num1 + num2
return sum
print "print output", add_two_numbers(1,1)
print "print output", add_two_numbers(1,2)
#loop
n = 1
while (n < 5):
print "n =", n
n = n +1
print "Loop finished "
for n in range(1, 5):
print"n =", n
print "Loop finished "
for i in range(0, 4):
if i == 2:
break
print i
print "Finished with i = ", str(i)
phrase = "it marks the spot"
for letter in phrase:
if letter == "ks":
print "yes ks"
break
else:
print "There was no 'X' in the phrase"
tries = 0
while tries < 3:
password = raw_input("Password: ")
if password == "ednalan":
break
else:
tries = tries +1
else:
print "Suspicious activity. The authorities have been alerted."
total = 0 # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total : ", total)
return total
# Now you can call sum function
sum( 10, 20 )
print ("Outside the function global total : ", total )
#-------------------------------------------------------------------
def add_two_numbers(num1, num2):
sum = num1 + num2
return sum
print(add_two_numbers(1,1)) #2
#---------------------------------------------------------------------
n = 1
while (n < 5):
print("n =", n)
n = n + 1
print("Loop finished")
#---------------------------------------------------------------------
numbers = [22, 34, 12, 32, 4]
sum = 0
i = len(numbers)
while (i != 0):
i -= 1
sum = sum + numbers[i]
print "The sum is: ", sum
#---------------------------------------------------------------------
import random
while (True):
val = random.randint(1, 30)
print val, # 14 14 30 16 16 20 23 15 17 22
if (val == 22):
break
#---------------------------------------------------------------------
import random
num = 0
while (num < 1000):
num = num + 1
if (num % 2) == 0:
continue
print num,
#---------------------------------------------------------------------
import random as rnd
for i in range(10):
print rnd.randint(1, 10), # 1 2 5 10 10 8 2 9 7 2
def root(x):
return x * x
#---------------------------------------------------------------------
def root(x):
return x * x
a = root(2)
b = root(15)
print a, b
#---------------------------------------------------------------------
x = 15
def function():
global x
x = 45
function()
print x # 45
#---------------------------------------------------------------------
print 4 in (2, 3, 5, 6)
for i in range(25):
print i, # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#---------------------------------------------------------------------
def gen():
x = 11
yield x
it = gen()
print it.next() # 11
#---------------------------------------------------------------------
def showModuleName():
print __doc__
def getModuleFile():
return __file__
a = showModuleName()
b = getModuleFile()
print a, b
#---------------------------------------------------------------------
def f():
"""This function prints a message """
print "Today it is a cloudy day"
print isinstance(f, object) # True
print id(f) # 3077407212
print f.func_doc # This function prints a message
print f.func_name # f
#---------------------------------------------------------------------
from math import sqrt
def cube(x):
return x * x * x
print abs(-1)
print cube(9)
print sqrt(81)
#---------------------------------------------------------------------
def showMessage(msg):
print msg
def cube(x):
return x * x * x
x = cube(3)
print x # 27
showMessage("Computation finished.") # Computation finished.
print showMessage("Ready.") # Ready.
#---------------------------------------------------------------------
n = [1, 2, 3, 4, 5]
def stats(x):
mx = max(x)
mn = min(x)
ln = len(x)
sm = sum(x)
return mx, mn, ln, sm
mx, mn, ln, sm = stats(n)
print stats(n) # (5, 1, 5, 15)
print mx, mn, ln, sm # 5 1 5 15
#---------------------------------------------------------------------
def C2F(c):
return c * 9/5 + 32
print C2F(100) # 212
print C2F(0) # 32
print C2F(30) # 86
#---------------------------------------------------------------------
def power(x, y=2):
r = 1
for i in range(y):
r = r * x
return r
print power(3) # 9
print power(3, 3) #27
print power(5, 5) # 3125
#---------------------------------------------------------------------
def display(name, age, sex):
print "Name: ", name
print "Age: ", age
print "Sex: ", sex
display("Lary", 43, "M") # Name: Lary Age: 43 Sex: M
display("Joan", 24, "F") # Name: Joan Age: 24 Sex: F
Cairo-Coders is the one place for high quality web development, Web Design and software development tutorials and Resources programming. Learn cutting edge techniques in web development, design and software development, download source components and participate in the community.
Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts
Python function and loop example code
Python Function and Loop Example code
PHP Month Array List Select Box Live-search
PHP Month Array List Select Box Live-search
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Month Array List Select Box Live-search</title>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<h2>PHP Month Array List Select Box Live-search</h2>
<p>This uses <a href="https://silviomoreto.github.io/bootstrap-select/">https://silviomoreto.github.io/bootstrap-select/</a></p>
<hr />
</div>
<?php
$lang_Date = array(
'Jan' =>'January',
'Feb' =>'February',
'Mar' =>'March',
'Apr' =>'April',
'May' =>'May',
'June' =>'June',
'July' =>'July',
'August' =>'August',
'Sep' =>'September',
'Oct' =>'October',
'Nov' =>'November',
'Dec' =>'December',
);
?>
<div class="row-fluid">
<select class="selectpicker" data-show-subtext="true" data-live-search="true">
<?php
foreach ($lang_Date as $key=>$value){
$selected = ($key==$function)?" Selected=\"Selected\"": "";
echo "<option data-subtext=\"$key\" $selected > $value </option>";
}
?>
</select>
<span class="help-inline">Try searching for November</span>
</div>
</div>
</body>
</html>
jQuery PHP checkbox values to PHP $_POST variables
jQuery PHP checkbox values to PHP $_POST variables
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery PHP checkbox values to PHP $_POST variables</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type = "text/javascript">
$(document).ready(function () {
$('#submitBtn').click (function() {
var selected = new Array();
$("input:checkbox[name=programming]:checked").each(function() {
selected.push($(this).val());
});
var selectedString = selected.join(",");
$.post("ajaxcheckboxvalue.php", {selected: selected },
function(data){
$('.result').html(data);
});
});
});
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<h1>jQuery PHP checkbox values to PHP $_POST variables</h1>
<div class="card" style="margin:50px 0">
<div class="card-header">Checkbox Animation</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">
Bootstrap Checkbox Default
<label class="checkbox">
<input type="checkbox" name="programming" value="Bootstrap Checkbox Default"/>
<span class="default"></span>
</label>
</li>
<li class="list-group-item">
Bootstrap Checkbox Primary
<label class="checkbox">
<input type="checkbox" name="programming" value="Bootstrap Checkbox Primary"/>
<span class="primary"></span>
</label>
</li>
<li class="list-group-item">
Bootstrap Checkbox Success
<label class="checkbox">
<input type="checkbox" name="programming" value="Bootstrap Checkbox Success"/>
<span class="success"></span>
</label>
</li>
<li class="list-group-item">
Bootstrap Checkbox Info
<label class="checkbox">
<input type="checkbox" name="programming" value="Bootstrap Checkbox Info"/>
<span class="info"></span>
</label>
</li>
<li class="list-group-item">
Bootstrap Checkbox Warning
<label class="checkbox">
<input type="checkbox" name="programming" value="Bootstrap Checkbox Warning"/>
<span class="warning"></span>
</label>
</li>
<li class="list-group-item">
Bootstrap Checkbox Danger
<label class="checkbox">
<input type="checkbox" name="programming" value="Bootstrap Checkbox Danger"/>
<span class="danger"></span>
</label>
</li>
</ul>
<div class = "result" style="padding:10px;"></div>
<button type="button" id = "submitBtn" class="btn btn-outline-success slideright" style="margin:10px;">Submit</button>
</div>
</div>
</div>
</div>
<style>
@keyframes check {0% {height: 0;width: 0;}
25% {height: 0;width: 10px;}
50% {height: 20px;width: 10px;}
}
.checkbox{background-color:#fff;display:inline-block;height:28px;margin:0 .25em;width:28px;border-radius:4px;border:1px solid #ccc;float:right}
.checkbox span{display:block;height:28px;position:relative;width:28px;padding:0}
.checkbox span:after{-moz-transform:scaleX(-1) rotate(135deg);-ms-transform:scaleX(-1) rotate(135deg);-webkit-transform:scaleX(-1) rotate(135deg);transform:scaleX(-1) rotate(135deg);-moz-transform-origin:left top;-ms-transform-origin:left top;-webkit-transform-origin:left top;transform-origin:left top;border-right:4px solid #fff;border-top:4px solid #fff;content:'';display:block;height:20px;left:3px;position:absolute;top:15px;width:10px}
.checkbox span:hover:after{border-color:#999}
.checkbox input{display:none}
.checkbox input:checked + span:after{-webkit-animation:check .8s;-moz-animation:check .8s;-o-animation:check .8s;animation:check .8s;border-color:#555}
.checkbox input:checked + .default:after{border-color:#444}
.checkbox input:checked + .primary:after{border-color:#2196F3}
.checkbox input:checked + .success:after{border-color:#8bc34a}
.checkbox input:checked + .info:after{border-color:#3de0f5}
.checkbox input:checked + .warning:after{border-color:#FFC107}
.checkbox input:checked + .danger:after{border-color:#f44336}
</style>
</body>
</html>
//ajaxcheckboxvalue.php
<?php
$selected = $_POST['selected'];
foreach ($selected as $value) {
echo $value . " <br/>";
}
?>
How to Load or Read XML file using PHP
How to Load or Read XML file using PHP
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>How to Load or Read XML file using PHP</title>
</head>
<body>
<?php
//Read Specific XML Elements
$xmldata = simplexml_load_file("xml/employee.xml") or die("Failed to load");
echo $xmldata->employee[0]->firstname . "<br/>";
echo $xmldata->employee[1]->firstname . "<br/>";
echo $xmldata->employee[2]->firstname;
?><br/><br/>
<?php
//Read XML Elements In A Loop
$xmldata = simplexml_load_file("xml/employee.xml") or die("Failed to load");
foreach($xmldata->children() as $empl) {
echo $empl->firstname . ", ";
echo $empl->lastname . ", ";
echo $empl->designation . ", ";
echo $empl->salary . "<br/>";
}
?>
<br/><br/>
<?php
$xml = simplexml_load_file('xml/employee.xml');
echo '<h2>Employees Listing</h2>';
$list = $xml->employee;
for ($i = 0; $i < count($list); $i++) {
echo 'Name: ' . $list[$i]->firstname . '<br>';
echo 'Salary: ' . $list[$i]->salary . '<br>';
echo 'Position: ' . $list[$i]->designation . '<br><br>';
}
?>
</body>
</html>
//employee.xml <?xml version="1.0"?> <company> <employee> <firstname>Emma</firstname> <lastname>Cruise</lastname> <designation>MD</designation> <salary>500000</salary> </employee> <employee> <firstname>Olivia</firstname> <lastname>Horne</lastname> <designation>CEO</designation> <salary>250000</salary> </employee> <employee> <firstname>Isabella</firstname> <lastname>Sophia</lastname> <designation>Finance Manager</designation> <salary>250000</salary> </employee> </company>
PHP Function create SEO URL Friendly
PHP Function create SEO URL Friendlystrtlower make string lowercase preg_replace remove all unwanted character spaces and dashes
<?php
function seo_url($string, $seperator='-') {
$string = strtolower($string);
$string = preg_replace("/[^a-z0-9_\s-]/", $seperator, $string);
$string = preg_replace("/[\s-]+/", " ", $string);
$string = preg_replace("/[\s_]/", $seperator, $string);
return $string;
}
$teststring = "PHP Function create SEO URL Friendly";
$seofrieldy = seo_url($teststring);
echo "www.tutorial.com/$seofrieldy/";
?>
Multiple Image Upload Php
Multiple Image Upload Phphow to upload multiple files using a single form
<?php
if (isset($_POST['Submit'])){
while(list($key,$value) = each($_FILES['images']['name']))
{
if(!empty($value))
{
$filename = $value;
$filename=str_replace(" ","_",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "img/$filename";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
}
}
}
?>
<table border='0' width='400' cellspacing='0' cellpadding='0' align=center>
<form method=post action="" enctype='multipart/form-data'>
<?php
$max_no_img=4;
for($i=1; $i<=$max_no_img; $i++){
echo "<tr><td>Images $i</td><td>
<input type=file name='images[]'></td></tr>";
}
?>
<tr><td colspan=2 align=center><input name="Submit" type=submit value='Add Image'></td></tr>
</form>
</table>
PHPMailer Upload mail Attachment
PHPMailer Upload mail Attachment
PHPMailer-master https://github.com/PHPMailer/PHPMailer
<?php
$msg = '';
if (array_key_exists('userfile', $_FILES)) {
if (preg_match('/\.(doc|docx|xls|xlsx|pdf|jpeg|png)$/i', $_FILES["userfile"]["name"])) //upload
{
$uploadfile = $_FILES['userfile']['name'];
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
// This should be somewhere in your include_path
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->setFrom('from@example.com', 'First Last');
$mail->addAddress('tomail@example.com', 'John Doe');
$mail->Subject = 'PHPMailer file sender';
$mail->msgHTML("My message body");
$mail->addAttachment($uploadfile);
if (!$mail->send()) {
$msg = "Mailer Error: " . $mail->ErrorInfo;
} else {
$msg = "Message sent!";
}
}else {
$msg = '<font color=red> ERROR_FAILED_TO_UPLOAD_FILE </font>';
}
}else{
$msg = '<font color=red> ERROR_FAILED_TO_UPLOAD_FILE </font>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>PHPMailer Upload mail Attachment</title>
</head>
<body>
<?php if (empty($msg)) { ?>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="100000"> Send this file: <input name="userfile" type="file">
<input type="submit" value="Send File">
</form>
<?php } else {
echo $msg;
} ?>
</body>
</html>
Using Stripe with PHP
Using Stripe with PHP
1. Setup the PHP SDK
We are going to use the Stripe PHP download on Github from Stripe.
2. HTML code index.html
1. Setup the PHP SDK
We are going to use the Stripe PHP download on Github from Stripe.
2. HTML code index.html
<html>
<head>
<title>stripe php</title>
<style>
.StripeElement {
background-color: white;
padding: 8px 12px;
border-radius: 4px;
border: 1px solid transparent;
box-shadow: 0 1px 3px 0 #e6ebf1;
-webkit-transition: box-shadow 150ms ease;
transition: box-shadow 150ms ease;
}
.StripeElement--focus {
box-shadow: 0 1px 3px 0 #cfd7df;
}
.StripeElement--invalid {
border-color: #fa755a;
}
.StripeElement--webkit-autofill {
background-color: #fefde5 !important;
}
</style>
</head>
<body>
<form action="charge.php" method="post" id="payment-form">
<div class="form-row">
<label for="card-element">Credit or debit card</label>
<div id="card-element">
<!-- a Stripe Element will be inserted here. -->
</div>
<!-- Used to display form errors -->
<div id="card-errors"></div>
</div>
<button>Submit Payment</button>
</form>
<!-- The needed JS files -->
<!-- JQUERY File -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Stripe JS -->
<script src="https://js.stripe.com/v3/"></script>
<!-- Your JS File -->
<script src="charge.js"></script>
</body>
</html>
3. charge.js file
// Stripe API Key
var stripe = Stripe('pk_test_Agw01Kg5ZpIuuzUwR8tGLUME'); //YOUR_STRIPE_PUBLISHABLE_KEY
var elements = stripe.elements();
// Custom Styling
var style = {
base: {
color: '#32325d',
lineHeight: '24px',
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSmoothing: 'antialiased',
fontSize: '16px',
'::placeholder': {
color: '#aab7c4'
}
},
invalid: {
color: '#fa755a',
iconColor: '#fa755a'
}
};
// Create an instance of the card Element
var card = elements.create('card', {style: style});
// Add an instance of the card Element into the `card-element` <div>
card.mount('#card-element');
// Handle real-time validation errors from the card Element.
card.addEventListener('change', function(event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
// Handle form submission
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
event.preventDefault();
stripe.createToken(card).then(function(result) {
if (result.error) {
// Inform the user if there was an error
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
stripeTokenHandler(result.token);
}
});
});
// Send Stripe Token to Server
function stripeTokenHandler(token) {
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('payment-form');
// Add Stripe Token to hidden input
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
// Submit form
form.submit();
}
4. charge.php file<?php
require_once('/stripe-php-6.10.3/init.php');
\Stripe\Stripe::setApiKey('sk_test_mnT9JSEucLntq5fFi5hdNlce'); //YOUR_STRIPE_SECRET_KEY
// Get the token from the JS script
$token = $_POST['stripeToken'];
// This is a $20.00 charge in US Dollar.
//Charging a Customer
// Create a Customer
$name_first = "Batosai";
$name_last = "Ednalan";
$address = "New Cabalan Olongapo City";
$state = "Zambales";
$zip = "22005";
$country = "Philippines";
$phone = "09306408219";
$user_info = array("First Name" => $name_first, "Last Name" => $name_last, "Address" => $address, "State" => $state, "Zip Code" => $zip, "Country" => $country, "Phone" => $phone);
$customer = \Stripe\Customer::create(array(
"email" => "rednalan23@gmail.com",
"source" => $token,
'metadata' => $user_info,
));
// Save the customer id in your own database!
// Charge the Customer instead of the card
$charge = \Stripe\Charge::create(array(
"amount" => 2000,
"description" => "Purchase off Caite watch",
"currency" => "usd",
"customer" => $customer->id,
'metadata' => $user_info
));
print_r($charge);
// You can charge the customer later by using the customer id.
//Making a Subscription Charge
// Get the token from the JS script
//$token = $_POST['stripeToken'];
// Create a Customer
//$customer = \Stripe\Customer::create(array(
// "email" => "paying.user@example.com",
// "source" => $token,
//));
// or you can fetch customer id from the database too.
// Creates a subscription plan. This can also be done through the Stripe dashboard.
// You only need to create the plan once.
//$subscription = \Stripe\Plan::create(array(
// "amount" => 2000,
// "interval" => "month",
// "name" => "Gold large",
// "currency" => "cad",
// "id" => "gold"
//));
// Subscribe the customer to the plan
//$subscription = \Stripe\Subscription::create(array(
// "customer" => $customer->id,
// "plan" => "gold"
//));
//print_r($subscription);
?>
Subscribe to:
Posts (Atom)



