Redirecting not working in PHP - php

I want to redirect to another page after inserting values in the database, but it is not redirecting. It remains on the same page. No error/warning is shown.
My code:
<?php
if (isset($_POST['btn-submit'])) {
$asth = $user->runQuery("SELECT MAX(Sr) as Sr FROM answer");
$asth->execute();
$aresult = $asth->fetch(PDO::FETCH_ASSOC);
$atf = ($aresult['Sr']);
$aI = "1";
$acid = $atf + $aI;
$arn = $fddate.$ydate.$mdate.$frandno.$acid;
$count = $i;
for ($j = 1; $j <= $count; $j++) {
$ufname = trim($_POST['radio'.$j]);
$Qrn = trim($_POST['qid'.$j]);
$istmt = $user->runQuery("INSERT INTO answer(ARN,Ans,QRN,SRN) VALUES(:user_arn, :user_crn, :user_qrn, :user_srn)");
$istmt->bindparam(":user_qrn",$Qrn);
$istmt->bindparam(":user_crn",$ufname);
$istmt->bindparam(":user_arn",$arn);
$istmt->bindparam(":user_srn",$srn);
$istmt->execute();
}
return $istmt;
$locationei = "result.php";
$locatione = $web.$locationei;
$user->redirect($locatione);
}
?>
In the starting of page:
require_once 'class.user.php';
$user = new USER();
In class.user.php:
public function redirect($url) {
header("Location: $url");
}

Your problem might lie in here:
return $istmt;
$locationei = "result.php";
$locatione = $web.$locationei;
$user->redirect($locatione);
Once you return a value, function stops execution and skips the rest of the code...
Also, you should ALWAYS exit() after redirection, as the redirection doesnt stop script execution and has been a source of problems in the past.
public function redirect($url)
{
header("Location: $url");
exit();
}

Related

$response->redirect not works

I have an IVR that plays some audios for the user and then I need to redirect to another php file. The strange thing is that this redirect does not work.
NOTE 1: the redirect that does not work is the last one ($response->redirect("./chooseLicense.php?rs=$rs"))
NOTE 2: if I put it in if(!is_object($rs)) it works perfectly.
Can anyone tell me why this happens?
Snippet of my code:
$rs = json_decode(Curl::post(baseUrl . "users/auth/", $cpfOrCnpj, $password));
// logText('rs in login', $rs);
if(!is_object($rs)) {
$gather->play("https://digital-lock-api.azurewebsites.net/ura-hmg/assets/audios/licenseNotFound.mp3");
}
if($rs->licenses === []) {
$gather->play("https://digital-lock-api.azurewebsites.net/ura-hmg/assets/audios/licenseNotFound.mp3");
}
if(count($rs->licenses) == 1) {
$licenseId = $rs->licenses[0]->id;
$isBlocked = $rs->licenses[0]->blocked;
$token = $rs->auth->token;
$response->redirect("./waitForFlip.php?licenseId=$licenseId&isBlocked=$isBlocked&token=$token");
}
if(count($rs->licenses) > 1) {
$count = 0;
foreach($rs->licenses as $license) {
$count++;
$gather->play("https://digital-lock-api.azurewebsites.net/ura-hmg/assets/audios/chooseLicense$count.mp3");
$gather->play($license->nicknameAudioUrl);
}
$rs = json_encode($rs);
logText("rs encode", $rs);
$response->redirect("./chooseLicense.php?rs=$rs");
}

else condition is working even if is true

I'm using codigniter 3.1.2 and using simple if condition in php but really confused when I checked my condition is true getting result from else condition as well and if as well mean getting data in from both cases.
public function editexperience($UserID = 0, $ID = 0) {
if ($this->Access->HaveAccess('Edit')) {
$Row = $this->Experience->Row($ID);
if ($ID > 0 && $Row){
print_r($Row);
Def(array(
'Update'=>'users/submit/updateexperience/'
),'Actions');
$User = $this->Model->Row(intval($UserID), '', 'CTRY.Currency');
$ID = intval($ID);
$Data['Row'] = $Row;
Def($Row,'Row');
$Data['Title'] = 'Edit Experience';
$Data['Fields'] = $this->GetExperienceFields($User->Currency, true);
$this->Main->SetPage('Helper/Edit', $Data, true);
} else {
TempNote('There is problem while getting request data!', 'Error');
redirect(URI(_E('{Page.List}'), true), 'refresh');
die();
}
}
}
In code I mentioned if I have Row then load template of edit.
Suppose:
I have Row and its loading edit template and also showing the error of else condition really confuse what is happening.
My PHP version is 5.6.31
TempNote Function
function TempNote($Message, $Type) {
//Prepare Data
$Current = array('Message'=>$Message,'Type'=>$Type);
//Get current instance
$Ins = & get_instance();
$Old = $Ins->Main->Messages;
// If another is already set and that should not be current
if (!empty($Old)) {
foreach ($Old as $Key=>$Now) {
if ($Now === $Current){
unset($Old[$Key]);
}
}
}
$Ins->Main->Messages[] = $Current;
$Ins->session->set_flashdata('Message', $Ins->Main->Messages);
}

How to Verify if XML tag exists with PHP from external server

Please apologyze my English.
I'm developing a kind of sitemap.xml system for my website to include products to my database from external websites, like Google did with his "Spiders", I just developed this whole script to verify if an specific sitemap.xml contains every required tags, and It works: If any tag is missing, the script returns an error, but if all "products" has the required tags, the script returns a success message.
But I only have one problem: if the xml external file has any error like a missing "close" tags, the script stop working and returns an error.
I need to verify the if the external xml file contais any error, and then proceed with the rest of the code that I wrote, if the result is "NO".
this is my developed script:
<?
$sitemap = htmlspecialchars(addslashes(stripslashes(strip_tags(trim($_POST['sitemap'])))));
$ref = htmlspecialchars(addslashes(stripslashes(strip_tags(trim($_POST['ver_id'])))));
error_reporting(E_ALL);
ini_set('display_errors', '1');
session_start();
include dirname(dirname(__FILE__))."/connectdb.php";
$query = "SELECT * FROM website WHERE `ver_id` = '$ref'";
$result = $mysqli->query($query);
/* array asociativo */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$url = $row['url'];
$long_url = $url.'/'.$sitemap;
?>
<?php
$total = 0;
$xml=simplexml_load_file("$long_url") or die("Error: Cannot create object");
$count = $xml->count();
foreach($xml->children() as $producto) {
$id = $producto->id;
$titulo = $producto->titulo;
$descripcion = $producto->descripcion;
$fotografia = $producto->fotografia;
$precio = $producto->precio;
$costo = $producto->costo;
$horario = $producto->horario;
$tiempo = $producto->tiempo;
$cobertura = $producto->cobertura;
$keywords = $producto->keywords;
$destacar = $producto->destacar;
$delivery = $producto->delivery;
if (!empty($id) && !empty($titulo) && !empty($descripcion) && !empty($fotografia) && !empty($precio) && !empty($costo) && !empty($horario) && !empty($tiempo) && !empty($cobertura) && !empty($keywords) && !empty($destacar) && !empty($delivery)) {
$total = $total + 1; } else { $total = $total - 1; }
}
if($total < $count){ header("Location:/user/sitio.php?id=$ref&mensaje=1"); } else
if($total == $count){
$query = "UPDATE website SET sitemap='$sitemap',sitemap_status='active' WHERE ver_id='$ref'";
$result = $mysqli->query($query);
header("Location:/user/sitio.php?id=$ref&mensaje=2");
}
?>
Solved with this simple script!
<?
$dom = new DOMDocument;
$dom->Load($long_url);
if ($dom->validate()) {
echo "Valid File";
} else { echo "Invalid File"; }
?>
thanks to everyone.

Compare last GPS and current GPS data

I have a project where i need to send GPS coordinates via. socket in every 6 seconds. The coordinates are stored in a MYsql database. I run a query every 6 seconds and if the last position is different from the current position the application sends the data to the remote server. In the browser it works like a charm but in the terminal i can't use Sessions.
I tried apc_add but according to the PHP manual it is removed a long time ago.
What is the most common way to do a comparsion like that? Store the last coordinates into the database or a text file? Or is there a way to sotore it in run time?
**Here is my main code: **
<?php
require 'bootstrap.php';
use App\Libs\appServiceProvider;
use App\Libs\socketServiceProvider;
use Socket\Raw\Factory;
use App\Models\Koordinata;
$app = new appServiceProvider;
if (empty($_SESSION['lat']) || empty($_SESSION['lon'])) {
$_SESSION['lat'] = 0;
$_SESSION['lon'] = 0;
}
$lastLat = $_SESSION['lat'];
$lastLon = $_SESSION['lon'];
$currentLat = $app->getAllCoordinatesByFszgId($application['fszgId'])->last()->lat;
$currentLon = $app->getAllCoordinatesByFszgId($application['fszgId'])->last()->lon;
if ($lastLat != $currentLat && $lastLon != $currentLon) {
$factory = new Factory();
$socket = $factory->createClient('REMOTEADDRESSE');
echo "Kapcsolat létrehozva\n";
$socket->write("MESSAGE");
echo "Üzenet elküldve\n";
var_dump("Válasz: " . $socket->read(8192));
$socket->close();
} else {
echo "Idle";
$log->addDebug("GPS data NOT CHANGED! STATUS IDLE!");
}
$_SESSION['lat'] = $app->getAllCoordinatesByFszgId($application['fszgId'])->last()->lat;
$_SESSION['lon'] = $app->getAllCoordinatesByFszgId($application['fszgId'])->last()->lon;
?>
Okay, I did it with database and works fine. Here is the code:
<?php
require 'bootstrap.php';
use App\Libs\appServiceProvider;
use App\Libs\socketServiceProvider;
use Socket\Raw\Factory;
use App\Models\Koordinata;
use App\Models\TempKoordinata;
$app = new appServiceProvider;
$last = TempKoordinata::find(1);
if(!empty($last)) {
$lastLat = $last->lat;
$lastLon = $last->lon;
} else {
$temp = new TempKoordinata();
$temp->id = 1;
$temp->lat = 0;
$temp->lon = 0;
$temp->save();
$log->addDebug('No data to compare! Empty tempCoordinate table! Set values to ZERO!');
}
$currentLat = $app->getAllCoordinatesByFszgId($application['fszgId'])->last()->lat;
$currentLon = $app->getAllCoordinatesByFszgId($application['fszgId'])->last()->lon;
if ($lastLat != $currentLat && $lastLon != $currentLon) {
/*$factory = new Factory();
$socket = $factory->createClient('REMOTE');
echo "Kapcsolat létrehozva\n";
$socket->write("MESSAGE");
echo "Üzenet elküldve\n";
var_dump("Válasz: " . $socket->read(8192));
$socket->close();*/
echo "Sending\n";
} else {
echo "Idle\n";
$log->addDebug("GPS data NOT CHANGED! STATUS IDLE!");
}
TempKoordinata::destroy(1);
//Elmentjük a mostani GPS koordinátát
$count = TempKoordinata::all();
//Ha üres az adatbázis akkor elmentjük a koordinátákat
if ($count->count() == 0) {
$temp = new TempKoordinata();
$temp->id = 1;
$temp->lat = $currentLat;
$temp->lon = $currentLon;
$temp->save();
} else {
$log->addDebug("More than one item in the temp table!");
}
?>

Decryption: Using a loop to go through a function using mysql

I'm trying to make some code that displays a user's passwords for transfer to a new website.
I have this right now.
function decryptPassword($users)
{
global $sql_tbl;
$userData=func_query_first("select * from $sql_tbl[customers] where login='".$users."'");
if ($userData["password"]!="") $password = text_decrypt($userData["password"]);
else return false;
return $password;
}
echo "master = ".decryptPassword('master')."<br>";
$a = decryptPassword('tester');
if ($a===false) { echo "User not found...";exit();}
echo "tester = ".decryptPassword('tester')."<br>";
?>
and it works, but I wanted to use a for each query and I have been having trouble trying to get it into a a loop. Should I be doing this differently?
function decryptPassword($users)
{
global $sql_tbl;
$userData=func_query_first("select * from $sql_tbl[customers] where login='".$users."'");
if ($userData["password"]!="") $password = text_decrypt($userData["password"]);
else return false;
return $password;
}
$email=msql_query("SELECT email
FROM $sql_tbl[address_book]
join xcart_customers on xcart_prod.xcart_address_book.userid=xcart_prod.xcart_customers.id
where (default_s = 'Y' and default_b='Y'and membershipid=2) or (default_s='N' and default_b='Y' and membershipid=2)");
while ($row = mysql_fetch_assoc($email)) {
foreach($row as $field) {
echo " = ".decryptPassword($field)."<br>";
$a = decryptPassword($field);
if ($a===false) { echo "User not found...";exit();}
echo "it#claramente.com = ".decryptPassword($field)."<br>";
}
}
Thanks for any help.

Categories