Redirect in PHP - Show txt file content - php

I'm just learning to code and I don't know my way around yet.
I already know how to redirect to another page with php.
for example you go to http://example.com/test.php/ then you are redirected to http://example.com/test.txt with the following code:
"header('Location: http://example.com/test.txt);"
But now I'm not sure how to show the content of different files on your domain if the requested url has
?data=1 or ?seid=2 after the php. For example:
"http://example.com/test.php?data=request1" shows the text from
"http://example.com/test1.txt"
"http://example.com/test.php?data=request2" shows the text from
"http://example.com/test2.txt"
Have informed me so far that I have found something with $DataArray but don't know exactly how to use it? I tried something with it:
<?php
$DataArray = array(
"request1" => "test1",
"request2" => "test2"
if(isset($_GET['data'])) {
$data = str_replace(" ", "+", $_GET["data"]);
if(array_key_exists($data, $DataArray))
echo trim(json_decode(file_get_contents('data/'. $DataArray[$data] .'.txt'),JSON_UNESCAPED_SLASHES), '"');
else
echo "badrequest";
}
?>
Sadly that doesn't work for me so I don't know how to manage that.
edit: was able to fix it thanks for your help.
result:
<?php
$targets = array("1" => "http://redirect-new.com/", "2" => "http://redirect-old.com/", /* ... */);
if (isset($_GET["data"]) && array_key_exists($_GET["data"], $targets)) {
header("Location: {$targets[$_GET["data"]]}");
exit;
}
?>

Pass the file name in the link without using the extension and try this code:
if(isset($_GET['data']))
{
$data = $_GET['data'];
$filename = $data.'.txt'; // here we will get the name of the file with the extension (.Text)
$FilePath = '/www/path/to/file'; // your directory files here
$Link = $FilePath.'/'.$filename;
/*
* Here we will find out whether the file exists or not :
*/
// if use include :
if(file_exists($Link)){
include $Link;
}else{
print 'No File Exist !';
}
// if use header location
if(file_exists($Link)){
header('Location: http://example.com/'.$Link);
}else{
print 'No File Exist !';
}
}
This will work with you, but you should read more about the HTTP protocol It will benefit you more in the future .

You need to learn a few things, let me try to help you complete a 'reading list' that will help you to understand what you're trying to do and how to do it.
First, you want to learn your way around HTTP protocol. It's a basic knowledge that will get you far - it's great to be aware of this protocol - it will help you identify what you need in different scenarios.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview
pay attention to http messages part.
Then, see how PHP abstracts different parts of HTTP protocol, here's the GET parameters:
https://www.php.net/manual/en/reserved.variables.get.php - something you will have to make use of.
Also you'll have to read files: https://www.php.net/manual/en/function.file-get-contents.php

Related

How to get current webpage name and echo with some modification

I am trying something strange with code i just want to know weather it is possible to perform a php code like this one
<?php
$cururl= ucfirst(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME));
$nexurlw = $cururl-1;
echo "$nexurlw";
?>
I have a problem in this code. My current page url is 30.php and i have a button on page "go to previous page" i want to change its url 29.php with the help of this function.
But this function echo 30 every time.
Try this :
$cururl = ucfirst(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME));
$intUrl = ((int) $cururl) - 1;
$nexurlw = (string) $intUrl.'.php';
echo "$nexurlw";
Even if it happens to be true in your case (because that's the default in a raw PHP installation) there's often no direct mapping between URL locations and filesystem objects (files / directories). For instance, this question's URL is
https://stackoverflow.com/questions/68504314/how-to-get-current-webpage-name-and-echo-with-some-modification but the Stack Overflow server does not have a directory called 68504314 anywhere on its disk.
You want to build a URL from another URL, thus there's no even any benefit in having the filesystem involved, you can just gather the information about current URL from $_SERVER['REQUEST_URI']. E.g.:
$previous_page_url = null;
if (preg_match('#/blah/(\d+)\.php#', $_SERVER['REQUEST_URI'], $matches)) {
$current_page_number = (int)$matches[1];
if ($current_page_number > 1) {
$previous_page_url = sprintf('/blah/%d.php', $current_page_number - 1);
}
}

How to get variables from a different PHP file without executing the code?

I am trying to loop through all the php files listed in an array called $articleContents and extract the variables $articleTitle and $heroImage from each.
So far I have the following code:
$articleContents = array("article1.php", "article2.php"); // array of all file names
$articleInfo = [];
$size = count($articleContents);
for ($x = 0; $x <= $size; $x++) {
ob_start();
if (require_once('../articles/'.$articleContents[$x])) {
ob_end_clean();
$entry = array($articleContents[$x],$articleTitle,$heroImage);
array_push($articlesInfo, $entry);
}
The problem is, the php files visited in the loop have html, and I can't keep it from executing. I would like to get variables from each of these files without executing the html inside each one.
Also, the variables $articleTitle and $heroImage also exist at the top of the php file I'm working in, so I need to make sure the script knows I'm calling the variables in the external file and not the current one.
If this is not possible, can you please recommend an alternative method?
Thanks!
Don't do this.
Your PHP scripts should be for your application, not for your data. For your data, if you want to keep it file-based, use a separate file.
There are plenty of formats to choose from. JSON is quite popular. You can use PHP's built-in serialization as well, which has support for more PHP-native types but is not as portable to other frameworks.
A little hacky but seems to works:
$result = eval(
'return (function() {?>' .
file_get_contents('your_article.php') .
'return [\'articleTitle\' => $articleTitle, \'heroImage\' => $heroImage];})();'
);
Where your_article.php is something like:
<?php
$articleTitle = 'hola';
$heroImage = 'como te va';
The values are returned in the $result array.
Explanation:
Build a string of php code where the code in your article scripts are wrapped inside a function that returns an array with the values you want.
function() {
//code of your article.php
return ['articleTitle' => $articleTitle, 'heroImage' => $heroImage];
}
Maybe you must do some adaptations to the strings due <?php ?> tags placements.
Anyway, this stuff is ugly. I'm very sure that it can be refactored in some way.
Your problem (probably) comes down to using parentheses with require. See the example and note here.
Instead, format your code like this
$articlesInfo = []; // watch your spelling here
foreach ($articleContents as $file) {
ob_start();
if (require '../articles/' . $file) { // note, no parentheses around the path
$articlesInfo[] = [
$file,
$articleTitle,
$heroImage
];
}
ob_end_clean();
}
Update: I've tested this and it works just fine.

How to make a php variable based on two variable that vary

So i have this code, $value2 is an array of values that I edit.
I have .txt document for each of the variable in the array.. for exemple
sometext_AA.txt
sometext_BB.txt
I currently have over 50 text files, and it make a BIG BIG BIG php files because i have the following code made for each of the files for exemple sometext_AA.txt...
I would like to make one script(the following) so that one script will work for all of my $value2(I do not delete the old texts files when the value are changed so i am unable to just make script to read all different text file, it has to be done that it read the active $value2 and process them...
I am not even sure if I am on the good way but i really hope someone can help me out.
Thank you!
$value2 = array("AA","BB","CC");
foreach($value2 as $value3) {
foreach($random1_' .$value3' as $random2_' .$value3') {
$random3_' .$value3' = 'sometext_.$value3'.txt;
$random4_' .$value3' = json_encode(file_get_contents($random3_' .$value3'));
echo $random4_' .$value3';
}
}
This is a exemple of current text i have in my file, I have a very big php file, and, id like a code to make it simple
foreach($random1_AA as $random2_AA) {
$random3_AA = 'sometext_AA.txt;
$random4_AA = json_encode(file_get_contents($random3_AA));
echo $random4_AA;
}
foreach($random1_BB as $random2_BB) {
$random3_BB = 'sometext_BB.txt;
$random4_BB = json_encode(file_get_contents($random3_BB));
echo $random4_BB;
}
foreach($random1_CC as $random2_CC) {
$random3_CC = 'sometext_CC.txt;
$random4_CC = json_encode(file_get_contents($random3_CC));
echo $random4_CC;
}
foreach($random1_DD as $random2_DD) {
$random3_DD = 'sometext_DD.txt;
$random4_DD = json_encode(file_get_contents($random3_DD));
echo $random4_DD;
}
I think that this is what you are looking for, using the $var_{$var_in_var} syntax that PHP allows (so you can include a variable in a variable name).
$value2 = array("AA","BB","CC");
foreach($value2 as $value3) {
foreach($random1_{$value3} as $random2_{$value3}) {
$random3_{$value3} = 'sometext_'.$value3.'.txt';
$random4_{$value3} = json_encode(file_get_contents($random3_{$value3}));
echo $random4_{$value3};
}
}
However, I stongly advise you to consider the following points in order to make your code maintainable:
Use appropriate variable names representing the real content of each variable (you shoud never use "value1", "value2", etc. as the name tells nothing about the variable content).
Don't use variables in variable names unless absolutely necessary, which is not your case. You can use arrays, which are better suited for doing that.
In fact, I don't even know what $random1_XX and $random2_XX are supposed to be. I don't see you defining them in the code sample you posted.
Here is an example of how clear and concise you code may be if you use my advice and if all you need to read all the files and print them in JSON format (which is the only thing the program sample you posted would be doing after corrections).
$file_codes = array('AA', 'BB', 'CC');
foreach($file_codes as $file_code) {
echo json_encode(file_get_contents('sometext_'.$file_code.'.txt'));
}
Of course, if you have anything else in your program (maybe some code using the variables $random3_XX and $random4_XX?), I cannot guess what it is so I can't really offer you help to optimize this code.

Why won't this regex work with file reading and PHP? It works for other files though

I have this code I have written to make my life easier when downloading .torrents, the code is as follows,
$file = 'http://kat.ph/new/';
if($file = file_get_contents($file)) {
// RETURN ALL MAGNET URIS FROM FILE
preg_match_all('/\"magnet\:\?xt\=urn\:btih\:(.*?)\"/x', $file, $magnetURI);
// FOR EACH MAGNET URI RETURNED
foreach($magnetURI[1] as $info) {
echo '' . $info . '<br /><br /><br /><br />';
}
} else {
echo '<strong>FAIL</strong>';
}
It is supposed to match magnet uri links and return them to me in easy to click links, it works on other websites try replacing the file with http://thepiratebay.se/recent/0, but for some reason the website in the example it will not work on?!?
Thanks for your help!
It works for me, try removing the x modifier.
The problem is the file_get_contents() call, apparently kat.ph doesn't like anonymous user agents, if you try to output the $file variable you get a bunch of garbage like:
��}�r�Ʋ�o�)&\ˑ\#�Aڒ�I���X���8Y;�r �! �Ĭ���� ϓ����. ��ey�ĥg�랾��;�u޻��:��Q6����9�Q�[e��E�~vv��J��Z�٬��=5��n-̒>Ũc�Q�O���ip�[s�(cQ&�&�F<�m������T^oD��e��l 7j���e��]K�K�ţ�ݚ�R/ &YG���x��|��gQS�D��dq�����~�ӌ�32�2HS8�,�B��)z��x'4M�S;uq�ӝ0�NH���Z��OG�e5����Q���zhd4<ŋ�u����Ug��o+�� �H�b�8ɼiFY��f0�C���oR��e*t2��x���Մ.߭L�����,�H��7]��Q�q=1fW� ��"?�!�{O/5��f��IH����[�DO�8Y#i�]i�S�5�R>�,=��SG��_�G��4o�,4�X�XcS� 36����wl�Vr�0D�_I�Ì%�X�*s�Q��$M�s4r| �֎�}$�g`+���0�c#7�'4S&�:|�~� ��$��S�d���y�����8 ��u{���M=P㩑����[oN����?��h`�/ћ}����R|�A � z;�0(�(���Q����=�8���>І[�ㆻF,��]��M����6!��=a4GW�+o���z��o۩s�s ]�0��H�b�����#�/d��Z�/ԕߌ6�P�|�gE�V���dz�ćz���|�zl�ɗ�)��i���e�$�/"��l�ʟ�) ���K�ʗx��Ʉ��:9'H�$�2�ؓP�,�r/��+Fcmq]�P|���n
Try setting the user agent to a known browser (via file_get_contents() HTTP context or CURL).

Phpmyadmin login script

I trying to code a login script for phpmyadmin
<?php
$user = "Domain";
$passwords = file("passwords.txt");
foreach ( $passwords as $pass){
$source = file_get_contents("http://dbadmin.one.com/index.php?lang=en&server=1&pma_username=$user&pma_password=$pass");
if(preg_match("/Database/", $source)):
echo "Login Worked with: {$pass}";
endif;
}
?>
My Problem is it , it dont works here
echo "Login Worked with: {$pass}";
Can you see the problem?
Not necessarily the solution to your problem, but some basic error checking might point you in the right direction. Your problem may even begin at the initial call to file.
$passwords = file("passwords.txt");
if (!$passwords) {
echo 'Unable to read password file';
} //etc
$source = file_get_contents("http://dbadmin.one.com/index.php?lang=en&server=1&pma_username=$user&pma_password=$pass");
if (!$source) {
echo 'Unable to read file source';
} //etc
Also as a side note if you were calling this function on a file outside your filesystem wouldn't you only get the output (HTML) similar to calling it in your browser (not sure if that was your intention).
$source = file_get_contents("http://dbadmin.one.com/index.php?lang=en&server=1pma_username=$user&pma_password=$pass");
if(preg_match("/Database/", $source)):
The value of $source is going to be the full HTML response of getting the url:
http://dbadmin.one.com/index.php?lang=en&server=1&pma_username=$user&pma_password=$pass
preg_match is only going to match on the first line of that string. You will need to parse the string differently or replace any newline characters so it will match on the whole file.
It also looks like you're testing logins to a database using the username "Domain" with a number of different passwords. Not sure if that was your intention, but it seems a bit odd.

Categories