What's a great way to have this operate as a class - php

I understand how classes are useful, but don't know what's the proper way to create ones that have prepared statements. I've started making a class and I want a method called isOnline that returns if the url is online.
// This is the code I'm trying to make a class.
global $db;
$stmt = $db->prepare("SELECT url FROM urls WHERE rel=? ORDER BY url");
$stmt->bind_param("i", $_SESSION['admin_id']);
$stmt->execute();
$result = $stmt->get_result();
?>
<?php
while($row = $result->fetch_array())
{
$url = $row['url'];
$site = strtolower($url);
// check if is online
$curl = curl_init();
curl_setopt_array( $curl, array(
CURLOPT_HEADER => true,
CURLOPT_NOBODY => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => 'https://'.$site ) );
$headers = explode( "\n", curl_exec( $curl ) );
$statushttp = $headers[0];
if(!$statushttp == 0){
}else{
$curl = curl_init();
curl_setopt_array( $curl, array(
CURLOPT_HEADER => true,
CURLOPT_NOBODY => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => 'http://'.$site ) );
$headers = explode( "\n", curl_exec( $curl ) );
$statushttp = $headers[0];
}
echo "$url with $statushttp <br>";
// email person here.
}
$stmt->free_result();

Not sure what you are doing to determine if a site is online or not but as far as creating a class to handle this. You should use something like this. If you can explain what you are doing to determine if a site is up or not I can update the class.
class SomeClassNameHere{
//this is the constructor of the class. This is ran when you create it
public SomeClassNameHere(){
}
//this is a public function that you can call
public function isOnline(){
//this is the first step to breaking up this into smaller peaces
//I moved your section of code that gets the urls from the database
//into a function that returns the rows from the database below.
$rows = getUrls();
while($row = $result->fetch_array()){
$site = strtolower($row['url']);
}
// check if is online
$curl = curl_init();
curl_setopt_array( $curl, array(
CURLOPT_HEADER => true,
CURLOPT_NOBODY => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => 'https://'.$site ) );
$headers = explode( "\n", curl_exec( $curl ) );
$statushttp = $headers[0];
if(!$statushttp == 0){
}else{
$curl = curl_init();
curl_setopt_array( $curl, array(
CURLOPT_HEADER => true,
CURLOPT_NOBODY => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => 'http://'.$site ) );
$headers = explode( "\n", curl_exec( $curl ) );
$statushttp = $headers[0];
}
//I wouldn't echo out the results here,
//I would have this function return a true or false and do the display
//somewhere else
//like this
if(statushttp == whateverIsTrue){ //remember to edit this
return true;
}else{
return false;
}
}
//this has the possibility to return more than one row. You will need to
//change your function to handle this.
public function getUrls(){
$stmt = $db->prepare("SELECT url FROM urls WHERE rel=? ORDER BY url");
$stmt->bind_param("i", $_SESSION['admin_id']);
$stmt->execute();
return $stmt->get_result();
}
}
To call this class you would want to do something like this.
//this is creating an instance of the class
$foo= new SomeClassNameHere();
//this will call the isOnline function of that class and return true or false
$siteOnline = $foo->isOnline();
if($siteOnline){
echo "Yeah!";
}else{
echo "Sad:-(";
}

Related

call of get payment status API FawryPay?

I'm trying to set an get payment status API with a payment processor. Below is the code they provided me. There are some information in the $result variable that I want, what I don't understand is what type of variable is '$result' and how can I take certain data from it. printing the $result shows "Transaction ID is : xxxx status is ACCEPTED". What I basically want is to take only the transaction ID and store it in a variable.
function payFawry($ID)
{
$ticket = get_row("select * FROM `tickets` WHERE ID = '$ID' and canceled = 0");
$user = get_row("select * from users where ID = '$ticket[clientID]'");
$amount = $ticket[cost].".00";
$customerMobile = substr($user[phone],-11);
$description = "Ticket ".$ticket[ID];
$merchantCode = "CsdsadasdasdasdasdasdaJasdasd";
$merchantRefNum = $ticket[ID];
$customerProfileId = $ticket[clientID];
$paymentMethod = "PAYATFAWRY";
$cardToken = "";
$customerEmail = substr($user[email]);
$secureKey = "sadasdsadafdsfasfasdasdasdasd";
$signature = $merchantCode.$merchantRefNum.$customerProfileId.$paymentMethod.$amount.$cardToken.$secureKey;
$signature = hash('sha256', $signature);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://atfawry.com/ECommerceWeb/Fawry/payments/charge',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{ \"merchantCode\":\"$merchantCode\", \"merchantRefNum\":\"$merchantRefNum\", \"customerProfileId\":\"$customerProfileId\", \"customerMobile\":\"$customerMobile\", \"customerEmail\":\"$customerEmail\", \"paymentMethod\":\"$paymentMethod\", \"cardToken\":\"$cardToken\", \"amount\":$amount, \"currencyCode\":\"EGP\", \"description\":\"$description\", \"paymentExpiry\":".strtotime('+3 hour')."077, \"chargeItems\":[ { \"itemId\":\"897fa8e81be26df25db592e81c31c\", \"description\":\"asdasd\", \"price\":$amount, \"quantity\":1 } ], \"signature\":\"$signature\" }",
CURLOPT_HTTPHEADER => array(
"Content-Type: application/json",
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$status = 1;
$response = json_decode ( $response , true ) ;
$referenceNumber = '<div style="font-size: 18px;line-height: 30px;margin-bottom: 9px;">Please proceed to any Fawry Retail (Kiosk, Supermarket) <br>Ask for Fawry Pay Service and enter you Reference Number: </div><div class="head-span" >'.$response[referenceNumber].'</div>';
$message = "برجاء استخدام رقم السداد $response[referenceNumber] لكود الخدمة 788 لدى فوري لتأكيد الحجز قم $ticket[ID]";
$new_password = encode_password($new_password) ;
send_sms($customerMobile ,$message);
$r = array("Status"=>$status,"Result"=>$referenceNumber,"referenceNumber"=>$response[referenceNumber],"Errors"=>"","NextStep"=>$NextStep);
return $r;
}
Returns 1 on success or 0 for non success
https://developer.fawrystaging.com/docs/server-apis/payment-notifications/get-payment-status-v2

HTTP Error 411. The request must be chunked or have a content length

So, I'm trying to make a promotion bot for Roblox using Webservices.
Here is what code I have:
<?php
$group_id = $_GET['groupId'];
$new_role_set_id = $_GET['newRoleSetId'];
$target_user_id = $_GET['targetUserId'];
$login_user = 'username=RPIRankBot&password=NoYou';
$file_path_rs = 'rs.txt';
$file_path_token = 'token.txt';
$current_rs = file_get_contents($file_path_rs);
$current_token = file_get_contents($file_path_token);
function getRS()
{
global $login_user, $file_path_rs;
$get_cookies = curl_init('https://www.roblox.com/newlogin');
curl_setopt_array($get_cookies,
array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => array("Content-Length: " . strlen($login_user)),
//CURLOPT_POSTFIELDS => $login_user
)
);
$rs = (preg_match('/(\.ROBLOSECURITY=.*?);/', curl_exec($get_cookies), $matches) ? $matches[1] : '');
file_put_contents($file_path_rs, $rs, true);
curl_close($get_cookies);
return $rs;
}
function changeRank($rs, $token)
{
global $group_id, $new_role_set_id, $target_user_id, $file_path_token;
$promote_user = curl_init("http://www.roblox.com/groups/api/change-member-rank?groupId=$group_id&newRoleSetId=$new_role_set_id&targetUserId=$target_user_id");
curl_setopt_array($promote_user,
array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HEADER => true,
CURLOPT_HTTPHEADER => array("Cookie: $rs", "X-CSRF-TOKEN: $token")
)
);
$resp = curl_exec($promote_user);
$resp_header_size = curl_getinfo($promote_user, CURLINFO_HEADER_SIZE);
$resp_header = substr($resp, 0, $resp_header_size);
$resp_body = substr($resp, $resp_header_size);
if (preg_match('/GuestData/', $resp_header)) {
$resp_body = changeRank( getRS(), $token );
} else if (preg_match('/Token Validation Failed/', $resp_header)) {
$new_token = (preg_match('/X-CSRF-TOKEN: (\S+)/', $resp_header, $matches) ? $matches[1] : '');
file_put_contents($file_path_token, $new_token, true);
$resp_body = changeRank( $rs, $new_token );
}
curl_close($promote_user);
return $resp_body;
}
echo changeRank($current_rs, $current_token);
This is giving me the HTTP Error 411. The request must be chunked or have a content length.
I've looked all around about this error, all of the scripts had the stuff to do with MySQL which wasn't what I was looking for. I know you have to supply a content header to the server, but I am confused as to how to do it.
Help would be greatly appreciated.

PHP Error on a Webserver

This is an auto promotion system (written in php) for a website, however it seems to give an error that I'm not familiar with. I replaced the website name with 'example' for privacy reasons.
<?php
$group_id = $_GET['groupId'];
$new_role_set_id = $_GET['newRoleSetId'];
$target_user_id = $_GET['targetUserId'];
$login_user = 'username=user&password=pass';
$file_path_rs = 'rs.txt';
$file_path_token = 'token.txt';
$current_rs = file_get_contents($file_path_rs);
$current_token = file_get_contents($file_path_token);
function getRS()
{
global $login_user, $file_path_rs;
$get_cookies = curl_init('https://www.example.com/newlogin');
curl_setopt_array($get_cookies,
array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_POST => true,
// CURLOPT_HTTPHEADER => array("Content-Length: " . strlen($login_user)),
CURLOPT_POSTFIELDS => $login_user
)
);
$rs = (preg_match('/(\.SECURITY=.*?);/', curl_exec($get_cookies), $matches) ? $matches[1] : '');
file_put_contents($file_path_rs, $rs, true);
curl_close($get_cookies);
return $rs;
}
function changeRank($rs, $token)
{
global $group_id, $new_role_set_id, $target_user_id, $file_path_token;
$promote_user = curl_init("http://www.example.com/groups/api/change-member- rank? groupId=$group_id&newRoleSetId=$new_role_set_id&targetUserId=$target_user_id");
curl_setopt_array($promote_user,
array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HEADER => true,
CURLOPT_HTTPHEADER => array("Cookie: $rs", "X-CSRF-TOKEN: $token")
)
);
$resp = curl_exec($promote_user);
$resp_header_size = curl_getinfo($promote_user, CURLINFO_HEADER_SIZE);
$resp_header = substr($resp, 0, $resp_header_size);
$resp_body = substr($resp, $resp_header_size);
if (preg_match('/GuestData/', $resp_header)) {
$resp_body = changeRank( getRS(), $token );
} else if (preg_match('/Token Validation Failed/', $resp_header)) {
$new_token = (preg_match('/X-CSRF-TOKEN: (\S+)/', $resp_header, $matches) ? $matches[1] : '');
file_put_contents($file_path_token, $new_token, true);
$resp_body = changeRank( $rs, $new_token );
}
curl_close($promote_user);
return $resp_body;
}
echo changeRank($current_rs, $current_token);
When accessing the page I get the page error:
Bad Request - Invalid Content Length
HTTP Error 400. There is an invalid content length or chunk length in the request.
I'm not sure why this is happening, and I've tried just about everything, even switching hosts, but the issue still arises. What can I do to fix this?

Instagram pagination

<?php
require 'db.php';
function callInstagram($url)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2
));
//catstagram start
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$tag = 'nypgraduation2014';
$client_id = "e4c623cb050444eeb7072e1a577da5b3";
$url = 'https://api.instagram.com/v1/tags/'.$tag.'/media/recent?client_id='.$client_id;
while (isset($url) && $url != '')
{
$inst_stream = callInstagram($url);
$results = json_decode($inst_stream, true);
foreach($results['data'] as $item)
{
$image_link = $item['images']['standard_resolution']['url'];
//$path_parts = pathinfo($image_link);
// save the file name in variable
//$image = ($path_parts['basename']);
//copy($image_link,"photos/" .$image);
mysql_query("INSERT INTO fypj131127cdb.instagramphoto(url) values('$image_link')");
// copy the file to you folder
}
$url = $result['pagination']['next_url'];
$image = "SELECT * FROM fypj131127cdb.instagramphoto ORDER BY ImageID ASC;";
$img_result=mysql_query($image);
$imageIndex = 0;
?>
Hi guys, I have trouble displaying all the instagram images with the hashtag #nypgraduation2014 using pagination. By using this codes, I don't know why I cannot display all the photos. As I am new to php and api, therefore I hope you guys can help me. Thanks!

How make my PHP code print to seperate divs?

I am trying to but the prints from this php code into seperate html div's so I can customize them with css. I got a css file made and it shows but everything is printed out into one div called body class=" hasGoogleVoiceExt".
<?php
class Bot {
public $botHost = '127.0.0.1';
public $botPort = 8087;
public $botId = NULL;
public $token = NULL;
public function __construct($botHost = '127.0.0.1', $botPort = 8087, $botId = NULL) {
$this->botHost = $botHost;
$this->botPort = $botPort;
if ($botId == NULL) {
$botId = $this->DefaultBot();
}
$this->botId = $botId;
}
public function DefaultBot() {
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'http://'.$this->botHost.':'.$this->botPort.'/api/v1/botId',
CURLOPT_RETURNTRANSFER => 1
));
$data = curl_exec($ch);
curl_close($ch);
$json = json_decode($data, TRUE);
return $json['defaultBotId'];
}
public function Login($username, $password) {
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'http://'.$this->botHost.':'.$this->botPort.'/api/v1/bot/login',
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POSTFIELDS => json_encode(array('username' => $username, 'password' => $password, 'botId' => $this->botId)),
CURLOPT_HTTPHEADER => array('Content-Type: application/json')
));
$data = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code != 200) return NULL;
$this->token = json_decode($data, TRUE)['token'];
}
public function GetInstances() {
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'http://'.$this->botHost.':'.$this->botPort.'/api/v1/bot/instances',
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => array('Authorization: bearer '.$this->token)
));
$data = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code != 200) return NULL;
$json = json_decode($data, TRUE);
return $json;
}
public function GetInstanceStatus($instanceId) {
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'http://'.$this->botHost.':'.$this->botPort.'/api/v1/bot/i/'.$instanceId.'/status',
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => array('Authorization: bearer '.$this->token)
));
$data = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code != 200) return NULL;
$json = json_decode($data, TRUE);
return $json;
}
}
$bot = new Bot('127.0.0.1', 8087);
$bot->Login('admin', 'foobar');
$instances = $bot->GetInstances();
for ($i = 0; $i < count($instances); $i++) {
$info = $bot->GetInstanceStatus($instances[$i]['uuid']);
if ($info['currentTrack'] != NULL && $info['playing']) {
printf("%s is playing %s by %s\n", $instances[$i]['nick'], $info['currentTrack']['title'], $info['currentTrack']['artist']);
} else {
printf("%s is not playing anything right now\n", $instances[$i]['nick']);
}
echo '<link href="botcss/styles.css" rel="stylesheet" type="text/css" />';
}
I'm currently testing it out here http://theunlighted.com/nowplaying.php
First things first: Your <link [...]> needs to be output before the for() loop.
Secondly, to output divs in a way (that I think you're meaning to do) is simple:
for($i = 0; $i < 123; $i++) {
echo '<div class="foo foo_'.$i.'">';
// do other output here.
echo '</div>';
}

Categories