Is there anyway to access variables of one php file into another?
- I am trying to validate a form. I need to access variables from the validationConditions.php file in form.php file.
I have tried creating sessions but they are error prone.
I am using the latest version of dreamweaver.
Is it possible to use $_POST to achieve the results?
Any example will be welcome...
Thanks a lot in advance.
The easiest would be to use session variables. In the first page you could set the values like this
session_start();
$_SESSION['myvar'] = 'My Data';
Then in the second page you can retrieve the data like this...
session_start();
$myvar = $_SESSION['myvar'];
Which in turn sets $myvar to "My Data"
You can read a php file with another php file. Assume that we have 2 php files.
new.php
<?php
$a="something";
?>
serach.php ---> search in new.php
<?php
// What to look for
$search = '$a'; //WE are searching $a
$lines = file('new.php'); // in new.php
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false)
echo $line;
}
?>
Something like that. You have to edit this file.
A somehow devious solution:
ob_start();
$request = array(
"_id"=>"0815",
"user"=>"john",
"email"=>"john#dunbar.com",
"phone"=>NULL
); // Don't know. Just how u need your request to look like.
include('validationConditions.php');
$response = getValidationConditions($request); // Function in 'validationConditions.php' that responds an array or a JSON
$out = ob_get_clean();
echo json_encode($out);
Related
Hi i have some values in 1.txt and want to show them in sequence one by one rather than random and also on click of a button not on reload. And i don't have much code on it. Can anyone help me with it please. ?
index.php:
<?php $lines = file('1.txt');?> <?php echo $lines[array($lines)];?>
1.txt in list format vertically:
1
2
3
4
5
Writing PHP like this is bad practice:
<?php $lines = ...;?> <?php echo ....;?>
Better write like this:
<?php
$lines = ...;
echo ...;
Now to your problem, you should use sort to order an array see: https://www.php.net/manual/de/function.sort.php
The best way to print an array in PHP is foreach:
foreach ($lines as $line) {
echo "\n<p>" . $line;
}
I'm not sure what your saying with the push of button and reload.
But this code assumes you mean, once the list has been generated keep it in the same order to this visitor.
I do that using a session variable so that even if the user reloads the page the order will be the same (for this user), but different between different users.
session_start();
if(empty($_session['lines'])){
$_session['lines'] = file('1.txt');
shuffle($_session['lines']);
}
// For debug:
echo implode("<br>\n", $_session['lines']);
i have a problem i couldn't figure out since im self-taught and still exploring the php world
so i have a text file that looks like this:
951753159
456787541
123156488
748651651
and i got an url with a variable
http://example.com/mypage.php?variable=951753159
what i want is to check if the url variable matches one of the txt file lines in order to execute a code
i already tried this
$search = $_GET["variable"];
$file = "variables.txt";
if (preg_match('/^' . $search . '$/m', file_get_contents($file))) {
THE CODE THAT I WANT TO EXECUTE
}
but for some reason it matches the whole content of the file
any help is highly appreciated
Thanks in advance :)
Try with an array from file():
$lines = file("variables.txt", FILE_IGNORE_NEW_LINES);
if(in_array($_GET["variable"], $lines)) {
// YES FOUND
} else {
// NOT FOUND
}
From the documentation on `file_get_contents', the entire contents of the file are read as a string. So that is why it is matching against the entire file.
The command that you want to use is file, this reads the file into an array of each line.
I would
Use file to read the file into an array.
Then array_flip the array so that it's values are now the keys
Which allows me to isset($array[$key])
You can do this.
<?php
#$search = $_GET["variable"];
$search = '123156488';
$file_txt = "content.txt";
$file = file($file_txt);//convert the txt in array
foreach ($file as $key => $value) {
if (trim($search) == trim($value)) {
print "DO something! " . $value;
}
}?>
Regards.
Nelson.
I am trying to write a php script to confirm an email address. I am using a file instead of a database to store user info which is outside the root directory. The file is csv.
When I try to store its contents in an array and print it, it works but when I try to compare an element from the array, it doesn't work. And also I want to write the email address of the user in csv as the last entry on the same line as other info.
Please help.
<?php
$rows[] = array();
$username = $_GET["username"];
$passkey = $_GET["passkey"];
$userdata = fopen("/****/*********/*****/$username.csv", "r");
$email = $_GET["email"];
$line = file_get_contents("/****/********/*****/$username.csv");
$rows = explode(",", $line);
print_r ($rows);
$newrows = trim($rows[6]);
$newpasskey = trim($passkey);
if($newrows == $newpasskey)
{
echo "Email-Id confirmed.";
fclose($userdata);
$userdata = fopen("/****/********/******/$username.csv", "a+");
fwrite($userdata, ",".$email);
fclose($userdata);
}
?>
I suggest you take a look at PHPs csv functions to ease loading/writing .csv data.
http://php.net/manual/en/function.fgetcsv.php and http://php.net/manual/en/function.fputcsv.php
Also, in your code, make sure that $username and $passkey are set, trimmed and sanitized before continuing.
You might also want to switch from GET to POST method in your form, I personally wouldn't want my password to be seen in the URL.
Try this:
$passkey = trim($passkey);
$stored_pass = trim($rows[6]);
if($stored_pass == $passkey)
{
//do stuff here
}
I found out the reason.I had made a mistake while entering the user info onto the file. I changed the php script that enters user info to the file. Now it works perfectly.
The .php file contains code like:
<?php
return array(
// commments...
'some_item' => 'abc',
// commments...
'some_other_item' => array(1, 2, 3),
...
);
What's the best way to "parse" this file somehow from within my PHP application, and be able to update data in it, without breaking formatting, code etc. ?
$content = require($file); will get the file's content (beware of relative paths and requirevs include semantics).
file_put_contents($file, '<?php return ' . var_export($content, true) . ';'); will write the content back to the file, but formatting will change. If you really need to keep the formatting, you could look into PHP Beautifier. It's not a perfect solution though.
simply include() the file:
$my_array = include 'myarray.php';
See example #4 at http://php.net/manual/en/function.include.php and http://php.net/manual/en/function.return.php
The best way is to include it; yes, include returns a value!
$data = include 'someData.php';
Assuming that your array has only two items
<?php
$myArray=include 'data.php';
$myArray[count($myArray)]='Item-3';
echo $myArray[2]; // Item-3
?>
Are you trying to load filenames which are contained in an array? If so:
$array_of_files = array('header.php','database.php','../inc/other_stuff.php');
foreach($array_of_files as $file)
{
include $file;
}
I'm creating a humble web browser-game in PHP. I'm making a "robbery" section...
I want to greet the user if he succeeds at a robbery. Some messages like "You're the man!", "A piece of cake, it was" etc.
I want more than, like, 5 different messages/notifications like this. How could I do this? how could I pick them from a .txt file, or have them imported from another PHP page which has these messages stored in variables to the "robbery" page...
Please, if you can provide a useful snippet of code, like a function for picking random messages, etc, that would be great.
Also if you can use OOP... :)
Thank you very much in advance...
This is a function that accepts a string (the filename) and reads the messages from it. It then returns the messages as an array so you can use them in your app.
<?php
function loadMessagesFromFile($file)
{
if(!file_exists($file))
{
return false;
}
$fh = fopen($file, 'r');
$messages = array();
while($data = fgets($fh))
{
$messages[] = $data;
}
fclose($fh);
return $messages;
}
$messages_from_file = loadMessagesFromFile('messages.txt');
$key = array_rand($messages_from_file);
echo $messages_from_file[$key];
Another option is storing the messages in PHP:
<?php
$messages = array('message', 'another message');
$key = array_rand($messages);
echo $messages[$key];
I don't see a specific need for an object here, just a function...
function message(){
$mes = array("Message 1","Message 2","Message 3","Message 4");
shuffle($mes);
return $mes[0];
}
That will give you a random message from one of the ones you put in the array. You could make as many messages as you like.
Or...
You could do an include file like you asked. I would again store them in an array in the include file then return a random message.
messages.php:
$mes = array("Message 1","Message 2","Message 3","Message 4");
index.php
include('messages.php');//be sure to include path to messages.php
shuffle($mes);
echo $mes[0];//will echo a random message
Put your messages into a file, one message per line, and then you can load that file into an array using file. The FILE_IGNORE_NEW_LINES flag will strip the newline from the end of each element in the returned array. Then you can shuffle the array to randomize it.
$messages = file('messages.txt', FILE_IGNORE_NEW_LINES);
shuffle($messages);
$message = $message[0]; // get the first of the shuffled $messages