A lot of versions around but i can not get it right...
I need to transfer variables from one php script file to another.
script1.php has the variables:
$t1 = $_POST['t1'];
$t2 = $_POST['t2'];
and I need to work with these variables in another script file - script2.php
How can I access these variables in script2.php file?
OK. i will post all the script.
script1.php or in fact getImage.php is following
<?php
$today = date("Ymd_His");
$t1 = $_POST['t1']; //mazais nosaukums
$t2 = $_POST['t2']; //lielais nosaukums
$c1 = $_POST['c1']; //kjeksis
$c2 = $_POST['c2']; //kjeksis
$c3 = $_POST['c3']; //kjeksis
$c4 = $_POST['c4']; //kjeksis
$mazais = $_POST['mazais']; //maza bilde atseviskji
$lielais = $_POST['lielais']; //maza bilde atseviskji
$response = "";
$error_response = "error.php";
$succes_response = "nextstep.php";
$etikjete = base64_decode($_REQUEST['png']);
if ($handle1 = fopen("render/".$today.'.png', 'w+')) {
if (!fwrite($handle1, $etikjete) === FALSE) {
fclose($handle1);
$response .= "Success etikjete! ";
} else {
$response .= "fwrite error etikjete! ";
$error = true;
}
} else {
$response .= "fopen error etikjete! ";
$error = true;
}
if($mazais){
$etikjete = base64_decode($mazais);
if ($handle1 = fopen("render/".$today.'_mazais.png', 'w+')) {
if (!fwrite($handle1, $etikjete) === FALSE) {
fclose($handle1);
$response .= "Success mazais! ";
} else {
$response .= "fwrite error mazais! ";
$error = true;
}
} else {
$response .= "fopen error mazais! ";
$error = true;
}
}
if($lielais){
$etikjete = base64_decode($lielais);
if ($handle1 = fopen("render/".$today.'_lielais.png', 'w+')) {
if (!fwrite($handle1, $etikjete) === FALSE) {
fclose($handle1);
$response .= "Success lielais! ";
} else {
$response .= "fwrite error lielais! ";
$error = true;
}
} else {
$response .= "fopen error lielais! ";
$error = true;
}
}
if($error){
echo $error_response;
} else {
echo $succes_response;
}
?>
and script2.php here is called nextstep.php
and in this nextstep.php I need to save the variables from getImage.php into database. nextstep.php so far is like this but does not work. connection with db is ok, if I set different independent variables on nextstep.php then they gets stored into db.
<?php
include 'getImage.php';
// Connects to your Database
mysql_connect("localhost", "user", "pass") or die(mysql_error()) ;
mysql_select_db("myDB") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO jos_orders (maza_bilde,liela_bilde,mazais_nosaukums,lielais_nosaukums)
VALUES ('$t1', '$c2', '$mazais', '$lielais')") ;
?>
How about these:
Session - store your data to session variables to that it can be retrieve to any pages of your site. The data will be cleared when you close your browser.
session_start();
$_SESSION['t1'] = $_POST['t1'];
$_SESSION['t2'] = $_POST['t2'];
Get Variable = Pass the variable through the URL
page2.php?t1=somevars&t2=somevars
$t1 = $_GET['t1'];
$t2 = $_GET['t2'];
3.$_COOKIE[] - http://www.w3schools.com/php/php_cookies.asp
You want to access the variables from a different script so it seems you are redirecting your script else all the global variables are accessible from any script as we know. So the solution can be session, else you if you are just doing some insert or update or delete action I suggest you submit it to the same page and include a file pass an action value check it from the included file perform the action according to that and redirect. Another solution is to built a small mvc application take a look at some mvc applications code I hope you can understand. Hope this will help you.
You can create them in $_SESSION[]
Check this out :
Storing Form Data as a Session Variable
Related
I've been working for the past 5 hours on why does this if get triggered...
Let me show you the code and explain you :
<?php
require_once "ConnectDB.php";
$link2 = $link;
$key = $posthwid = "";
$err = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["key"])){
$err = "Thanks for the ip (" .$_SERVER['REMOTE_ADDR']. "), have a good day! (1)";
}
else{
$key = trim($_POST["key"]);
}
$hwid = $_POST["hwid"];
if(empty($err)){
$sql = "SELECT hwid, idkey, length, created_at FROM money WHERE idkey = '" .$key. "'";
$row = mysqli_query($link, $sql);
if(mysqli_num_rows($row) < 2){
while($result = mysqli_fetch_assoc($row)) {
if($result["idkey"] == $key)
{
$err = "key";
if($result["hwid"] == "")
{
$err = "nohwid";
$sql2 = "UPDATE IceCold SET hwid = '" .$hwid. "' WHERE idkey = '" .$key. "'";
if(mysqli_query($link2, $sql2)){
$hwid = $result["hwid"];
mysqli_close($link2);
echo "debug";
}
else {
$err = "Oops! Something went wrong. Contact the support.";
}
}
if ($hwid !== $result["hwid"]) {
$err = "Contact the support";
}
elseif($_SESSION["admin"] == true) {
//Do special stuff
}
else {
///do other checks
if($created_at > $date){
$err = $hwid;
} else {
$err = "The key date is too old, buy a new one.";
}
}
}
else{
$err = "The key you entered was not valid.";
}
} mysqli_close($link);
} else {
$err = "multiple entry, contact support";
}
}
} else {
$err = "Thanks for the ip (" .$_SERVER['REMOTE_ADDR']. "), have a good day! (3)";
}
echo $err;
?>
So basically, I have this Connect DB file with a mysqli_connect called $link and I'm designing a liscence API for my program. My program will send a request with the "idkey" and "hwid" and is waiting for the hwid to come back. I have an entry in my sql databse with only a key registered and I've trying to make my program wotk by generating POST request with the id and a random hwid but I've found no success. If variables are weirdly moved around, It's because of the debugging.
Right now, with my current setup, I get the Contact the support response which I don't understand why?!? The request and the key are correct if I'm able to get this awnser.
It's probably a stupid mistake but I jsut can't figure it out...
Thanks in advance for your help
Edit: the if statement I'm referring to is this:
if($hwid !== $result["hwid"])
There was a typo in the code that I fixed but it wasn't the issue,
as for the elseif, that would destroy the order of execution of the code and destroy the logic behind it(If that made sense).
Weirdly, after some tests, I found out that the second SQL request I send doesn't want to be executed ($sql2) and there is no error in httpd logs... Can you execute two requests? I tried to create $link2 but it doesn't change anything
EDIT : Found solution
if($result["hwid"] == "")
{
$sql2 = "UPDATE money SET hwid = '" .$_POST["hwid"]. "' WHERE idkey = '" .$key. "'";
if(mysqli_query($link2, $sql2)) {
$newhwid = $_POST["hwid"];
mysqli_close($link2);
}
else {
$err = "Oops! Something went wrong. Contact the support.";
}
}
elseif ($_POST["hwid"] != $result["hwid"]) {
$err = "Contact the support";
}
if($_POST["hwid"] == $newhwid || $_POST["hwid"] == $result["hwid"] ) {
/// do other checks
}
The condition before that one, if($row['hwid'] = ""), is an assignment. This code is changing the value of $row['hwid'] to an empty string, causing the condition after it to be true. I assume you meant to write == to test if $row['hwid'] is empty; otherwise it doesn't make sense to write this as an if statement.
By the way, it's not clear whether this if statement shouldn't be an else if. The rest of the branches here are else if (or elseif, which is the same in PHP), so you should consider whether you have missed out an else on this one too.
The data is not inserting into another table, here's the code below :
if (isset($_POST))
{
$job = $_POST['jobtitle'];
$dur = $_POST['duration'];
$deg = $_POST['requireddegree'];
$exp = $_POST['experiance'];
$sal = $_POST['salary'];
$mark = $_POST['marks'];
if ( !empty($job) && !empty($dur) && !empty($deg) && !empty($exp) && !empty($sal) && !empty($mark))
{
$dur = mysql_real_escape_string($dur);
$deg= mysql_real_escape_string($deg);
$exp = mysql_real_escape_string($exp);
$sal = mysql_real_escape_string($sal);
$mark = mysql_real_escape_string($mark);
$job = mysql_real_escape_string($job);
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('".$dur."','".$deg."','".$exp."','".$sal."','".$mark."','".$job."') ";
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
With this it gives me server error or there was an error in CGI script.But when I write the variables in this form '$dur' instead of '".$dur." then the else conditon runs after insert query and displays data is not inserted.
However, i have written the same logic while inserting data in my another table and it inserts successfully.But there I put '$dur'.
I can't find the problem.Will be glad for your suggestions :)
I can't seem to find any other error by seeing this code expect for
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('$dur','$deg','$exp','$sal','$mark','$job') ";
//Use ".$job." only for stuff like '".md5($_POST['password'])."' otherwise this creates problem some times.
// Adding this always helps
if(!mysqli_query($con,$query))
{
die('error'.mysqli_error($con));
}
// in $con = $con=mysqli_connect("localhost","root","");
else
{
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
I think by making these changes and making sure that your db name and other basic stuff are correct then you should be good to go otherwise, specify your exact error.
I'm currently building a system for a football league. And are currently working on the script file for adding results. Most of the script works and the result is always successfully added to the database. However the authentication part seems to fail. The if statement on line 12 does not seem to fire and I can't understand why.
My code can be found in the pastebin link here: http://pastebin.com/ty4pdGgn
<?PHP
include 'functions.php';
dbConnect();
//$userEmail = mysql_real_escape_string($_POST["userEmailText"]);
$userCode = mysql_real_escape_string($_POST["userPasscodeText"]);
$authenticated = false;
$userEmail = "info#example.com";
if ($userEmail == "info#example.com") {
header('Location: ../results.php?error=authentication');
}
$allUsers = mysql_query("SELECT * FROM accounts WHERE email = '$userEmail'");
while ($thisUser = mysql_fetch_assoc($allUsers)){
if ($userCode != $thisUser['passCode']) {
header('Location: ../results.php?error=authentication2');
}
echo $thisUser['passCode'];
$authenticated = true;
$userID = $thisUser['userID'];
}
if (!$authenticated) {
header('Location: ../results.php?error=authentication3');
}
$dateSubmitted = $_POST['submissionDate'];
$homeTeam = $_POST['homeTeam'];
$awayTeam = $_POST['awayTeam'];
$homeGoals = $_POST['homeGoals'];
$awayGoals = $_POST['awayGoals'];
if ($homeTeam == $awayTeam) {
header("Location: ../results.php?error=team");
}
if (getTeamLeague($homeTeam) != getTeamLeague($awayTeam)) {
header("Location: ../results.php?error=league");
} else {
$leagueID = getTeamLeague($homeTeam);
}
if ($homeGoals > $awayGoals) {
$winnerID = $homeTeam;
} else if ($homeGoals < $awayGoals) {
$winnerID = $awayTeam;
} else if ($homeGoals == $awayGoals) {
$winnerID = -1;
}
$cQuery = mysql_query("INSERT INTO results VALUES ('', $userID, '$dateSubmitted', $leagueID, $homeTeam, $homeGoals, $awayTeam, $awayGoals, $winnerID, 0)");
if ($cQuery){
header('Location: ../results.php');
} else {
echo mysql_error();
}
?>
Any help with this matter will be much appreciated. The functions.php contains no errors as this is all to do with database entry and not the authentication.
Put a die(); after the header("Location:...");
As your comparison code (the "if" part on line 12) that you pasted has to work, i have two advice:
Put a die(); or exit(); after the header() part.
Try looking here, as I am not sure if header() will work, while the location path you set is relative. Basic advice is to always use base paths for redirects, like "http://your.site.com/script.php").
I have written a simple application which has login page. After login search insertion buttons are there. I build this simple application and run successfully last month. But now when i am using this now my pages are not redirecting to next page. i double checked my syntax.
i googled for the answer and found ob_start() method. And now my application is running successfully.
when the first time i have used this application i didn't use ob_start. But why its not working now without the ob_start(); method.
Please explain.
Search function :
$email = $_POST['search'];
$sql = "select * from employee_details where ";
if($email){
$sql .= " email = '$email' ";
}
$rv = mysql_query($sql);
if(mysql_num_rows($rv) == 0){
$errmsg_arr[] = "Employee records are not found.";
$page = "HomePage.php";
$errflag = true;
errors($page,$errmsg_arr, $errflag );
}
while( $row = mysql_fetch_array($rv)){
$var['employee_id'] = $row['employee_id'];
$var['employeename'] = $row['employee_name'];
$var['email'] = $row['email'];
$var['phone'] = $row['phone'];
$var['address1'] = $row['address1'];
$var['state'] = $row['state'];
$var['country'] = $row['country'];
}
addvars($var);
header("location: EmployeeDetails.php");
addvars function:
function addvars($vars) {
session_start();
$_SESSION[] = array();
foreach($vars as $keys => $vals) {
$_SESSION[$keys] = $vals;
}
}
Errors Function:
function errors($page,$errmsg_arr, $errflag){
if($errflag) {
session_start();
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: $page");
exit();
}
}
Most likely because you try to set headers when they're already sent out. (you can try to adjust output buffering instead of using ob_start if it bothers you).
I'm having a problem with my PHP and MySQL project . I wanted to insert multi collumn value into the database but the truth is, im already confused by the codes. it's like this if you would like to take a look:
if(!empty($_POST['brando'])){
$A="brand = '$brando'";}
else{
$A=" ";}
if(!empty($_POST['prnameo'])){
$B="product_name = '$prnameo'";}
else{
$B=" ";}
if(!empty($_POST['prido'])){
$C="product_id = '$prido'";}
else{
$C=" ";}
if(!empty($_POST['prcolo'])){
$D="color = '$prcolo'";}
else{
$D=" ";}
if(!empty($_POST['priceo'])){
$E="price = '$priceo'";}
else{
$E=" ";}
$sqlq="UPDATE $tbl_name2 SET $A $B $C $D $E where id='$id'";
mysql_query($sqlq);
I noticed that querying multivalue command into a database requires comma such as:
mysql_query("UPDATE $tablename SET collumn1='value', collum2='value' where id='value'");
and now i cant put any comma or "," in any of those codes, making the PHP page unable to send other variable values into the server.
even if i change the coding to this:
$sqlq="UPDATE $tbl_name2 SET $A , $B , $C , $D , $E where id='$id'";
it'll produce what else but damn errors.
so i would like to ask for help if you know what i'm talking about. i know, it sounds like i've been stressed out by the codings.
ooh, this code too, i forgot to put it for these.
for ($help_given=1, $help_given++)
{
echo "Thanks";
}
Try to implode() an array with "," ,like this:
<?php
if(!empty($_POST['brando'])){
$value[] ="brand = '$brando'";
}
if(!empty($_POST['prnameo'])){
$value[] ="product_name = '$prnameo'";
}
if(!empty($_POST['prido'])){
$value[] ="product_id = '$prido'";
}
if(!empty($_POST['prcolo'])){
$value[] ="color = '$prcolo'";
}
if(!empty($_POST['priceo'])){
$value[] ="price = '$priceo'";
}
$sqlq="UPDATE $tbl_name2 SET " . implode(",",$value)." where id='$id'";
mysql_query($sqlq);
?>
Then, you'd better to use "mysql_escape_string" or "PDO::prepare" method to prevent SQL injection.
if(isset($_POST['brando']))
{
$brando=mysql_escape_string($_POST['brando']);
$A="brand = ".$brando;
}
else
{
$A=" ";
}
if(isset($_POST['prnameo']))
{
$prnameo=mysql_escape_string($_POST['prnameo']);
$B="product_name = ".$prnameo;
}
else
{
$B=" ";
}
if(isset($_POST['prido']))
{
$prido=mysql_escape_string($_POST['prido']);
$C="product_id = ".$prido;
}
else
{
$C=" ";
}
if(isset($_POST['prcolo']))
{
$prcolo=mysql_escape_string($_POST['prcolo']);
$D="color= ".$prcolo;
}
else
{
$D=" ";
}
if(isset($_POST['priceo']))
{
$priceo=mysql_escape_string($_POST['priceo']);
$E="price = ".$brando;
}
else
{
$E=" ";
}
$tbl_name="mytable";//to set
$id='primary_key';//to set
$sqlq="UPDATE $tbl_name SET $A, $B, $C, $D, $E where id='$id'";
mysql_query($sqlq);
Just put values where I have commented as //to set...