Creating variables dynamically with PHP - php

I'm working on a REST styled API, and I want to be able to break the URL down into individual variables.
Say I have the following URL: www.example.com/user/post/1
I'd like to make the following variables:
$uri_1 = user
$uri_2 = post
$uri_3 = 1
I tried to do this but it got stuck in a loop
$path = explode('/', $this->path($uri));
for($i=0;$i < count($path);$i++){
$uri_.$i = $path[i];
}

$url = explode('/', strtolower(trim($_SERVER['REQUEST_URI'], '/')));
$uri_1 = isset($url[0])?$url[0]:'';
$uri_2 = isset($url[1])?$url[1]:'';
$uri_3 = isset($url[2])?$url[2]:'';

Here's how you do it for an arbitrary number of variables, using PHP's variable variables feature:
$path = explode('/', $this->path($uri));
for($i=0;$i < count($path);$i++){
${"uri_".$i} = $path[i];
}

Related

Need to change url using php

I am going to make a URL checking system.
I have this URL
https://lasvegas.craigslist.org/mob/6169799901.html
Now I want to make this URL like this
https://lasvegas.craigslist.org/search/mob?query=6169799901
how can I do it using PHP?
Since I ended up (maybe?) solving it anyways, here's one method using URL/path parsing:
$url = 'https://lasvegas.craigslist.org/mob/6169799901.html';
$parsed = parse_url($url);
$basepath = pathinfo($parsed['path']);
echo $parsed['scheme'].
"://".
$parsed['host'].
"/search".
$basepath['dirname'].
"?query=".
$basepath['filename'];
Formatted for readability.
https://3v4l.org/E6Y54
Try this
$url = "https://lasvegas.craigslist.org/mob/6169799901.html";
$id = substr($url, strrpos($url, '/') + 1);
$id = str_replace(".html","",$id);
$result = "https://lasvegas.craigslist.org/search/mob?query=".$id;
echo $result;

Can we Use Replace By str_replace in a code fetched from remote url

i got Source Code From Remote Url Like This
$f = file_get_contents("http://www.example.com/abc/");
$str=htmlspecialchars( $f );
echo $str;
in that code i want to replace/extract any url which is like
href="/m/offers/"
i want to replace that code/link as
href="www.example.com/m/offers/"
for that i used
$newstr=str_replace('href="/m/offers/"','href="www/exmple.com/m/offers/',$str);
echo $newstr;
but this is not replacing anything now i want to know 1st ) can i replace by str_replace ,in the code which is fetched from remote url and if 'yes' how ...? if 'no' any other solution ?
There will not be any " in your $str because htmlspecialchars() would have converted them all to be " before it got to your str_replace.
I start assuming all href attributes belong to tags.
Since we know if all tags are written in the same way. instead of opting for regular expressions, I will use an interpreter to facilitate the extraction process
<?php
use Symfony\Component\DomCrawler\Crawler;
$base = "http://www.example.com"
$url = $base . "/abc/";
$html = file_get_contents($url);
$crawler = new Crawler($html);
$links = array();
$raw_links = array();
$offers = array();
foreach($crawler->filter('a') as $atag) {
$raw_links[] = $raw_link = $atag->attr('href');
$links[] = $link = str_replce($base, '', $raw_link);
if (strpos($link, 'm/offers') !== false) {
$offers[] = $link;
}
}
now you have all the raw links, relative links and offerslinks
I use the DomCrawler component

Replace the page from a url using php

I have this type of urls stored in a php variable:
$url1 = 'https://localhost/mywebsite/help&action=something';
$url2 = 'https://localhost/mywebsite/jobs&action=one#profil';
$url3 = 'https://localhost/mywebsite/info&action=two&action2=something2';
$url4 = 'https://localhost/mywebsite/contact&action=one&action2=two#profil';
I want to replace the page help, jobs, info, contact with home in a very simple way, something like this:
echo replaceUrl($url1);
https://localhost/mywebsite/home&action=something
echo replaceUrl($url2);
https://localhost/mywebsite/home&action=one#profil
echo replaceUrl($url3);
https://localhost/mywebsite/home&action=two&action2=something2
echo replaceUrl($url4);
https://localhost/mywebsite/home&action=one&action2=two#profil
So here is the solution i found:
function replaceUrl($page){
$pieces = explode("/", $page);
$base = '';
for ($i=0; $i<count($pieces)-1; $i++) $base .= $pieces[$i].'/';
$hash = strpbrk($pieces[count($pieces)-1], '&#');
return $base.'home'.$hash;
}
You'll want to add something like
RedirectMatch 301 help(.*) home$1
to your .htaccess file. I'm not sure PHP is the correct tool for the job.
If you actually want to modify a string with the value of that (which is what your tags and.. comments indicate), you'll want to do:
$url = "https://localhost/mywebsite/help&action=something#profil"
$url = str_replace("help", "home", $url);
echo $url; // https://localhost/mywebsite/home&action=something#profil

URL Replacement in PHP

I'm trying to change a value in a string that's holding my current URL. I'm trying to get something like
http://myurl.com/test/begin.php?req=&srclang=english&destlang=english&service=MyMemory
to look like
http://myurl.com/test/end.php?req=&srclang=english&destlang=english&service=MyMemory
replacing begin.php for end.php.
I need the end.php to be stored in a variable so it can change, but begin.php can be a static string.
I tried this, but it didn't work:
$endURL = 'end.php';
$beginURL = 'begin.php';
$newURL = str_ireplace($beginURL,$endURL,$url);
EDIT:
Also, if I wanted to replace
http://myurl.com/begin.php?req=&srclang=english&destlang=english&service=MyMemory
with
http://newsite.com/end.php?req=&srclang=english&destlang=english&service=MyMemory
then how would I go about doing that?
Assuming that you want to replace the script filename of the url, you can use something like this :
<?php
$endURL = 'end.php';
$url ="http://myurl.com/test/begin.php?req=&srclang=english&destlang=english&service=MyMemory";
$pattern = '/(.+)\/([^?\/]+)\?(.+)/';
$replacement = '${1}/'.$endURL.'?${3}';
$newURL = preg_replace($pattern , $replacement, $url);
echo "url : $url <br>";
echo "newURL : $newURL <br>";
?>
How do you want them to get to end.php from beigin.php? Seems like you can just to a FORM submit to end.php and pass in the variables via POST or GET variables.
The only way to change what page (end.php, begin.php) a user is on is to link them to another page from that page, this requires a page refresh.
I recently made a PHP-file for this, it ended up looking like this:
$vars = $_SERVER["QUERY_STRING"];
$filename = $_SERVER["PHP_SELF"];
$filename = substr($filename, 4);
// for me substr removed 'abc/' in the beginning of the string, you can of course adjust this variable, this is the "end.php"-variable for you.
if (strlen($vars) > 0) $vars = '?' . $vars;
$resultURL = "http://somewhere.com" . $filename . $vars;

keeping url parameters during pagination

Is there any way to keep my GET parameters when paginating.
My problem is that I have a few different urls i.e
questions.php?sort=votes&author_id=1&page=3
index.php?sort=answers&style=question&page=4
How in my pagination class am I supposed to create a link to the page with a different page number on it but yet still keep the other parts of the url?
If you wanted to write your own function that did something like http_build_query, or if you needed to customize it's operations for some reason or another:
<?php
function add_edit_gets($parameter, $value) {
$params = array();
$output = "?";
$firstRun = true;
foreach($_GET as $key=>$val) {
if($key != $parameter) {
if(!$firstRun) {
$output .= "&";
} else {
$firstRun = false;
}
$output .= $key."=".urlencode($val);
}
}
if(!$firstRun)
$output .= "&";
$output .= $parameter."=".urlencode($value);
return htmlentities($output);
}
?>
Then you could just write out your links like:
Click to go to page 2
You could use http_build_query() for this. It's much cleaner than deleting the old parameter by hand.
It should be possible to pass a merged array consisting of $_GET and your new values, and get a clean URL.
$new_data = array("currentpage" => "mypage.html");
$full_data = array_merge($_GET, $new_data); // New data will overwrite old entry
$url = http_build_query($full_data);
In short, you just parse the URL and then you add the parameter at the end or replace it if it already exists.
$parts = parse_url($url) + array('query' => array());
parse_str($parts['query'], $query);
$query['page'] = $page;
$parts['query'] = http_build_str($query);
$newUrl = http_build_url($parts);
This example code requires the PHP HTTP module for http_build_url and http_build_str. The later can be replaced with http_build_query and for the first one a PHP userspace implementation exists in case you don't have the module installed.
Another alternative is to use the Net_URL2 package which offers an interface to diverse URL operations:
$op = new Net_URL2($url);
$op->setQueryVariable('page', $page);
$newUrl = (string) $op;
It's more flexible and expressive.
How about storing your page parameter in a session, so you don't have to modify every single page url?

Categories