$url = $_SERVER['REQUEST_URI'];
$url = basename($url).PHP_EOL;
switch ($url) {
case 'digital-marketing-and-seo':
$new_url = "Digital Marketing & SEO";
break;
case 'websites-digital-destinations':
$new_url = "Websites & Digital Destinations";
break;
case 'brand-identity-evolution':
$new_url = "Brand Identity & Evolution";
break;
case 'strategy-consulting':
$new_url = "Strategy & Consulting";
break;
case 'government-universities':
$new_url = "Government & Universities";
break;
case 'hospitality-travel':
$new_url = "Hospitality & Travel";
break;
case 'architecture-engineering':
$new_url = "Architecture & Engineering";
break;
case 'wine-spirits':
$new_url = "Wine & Spirits";
break;
default:
$new_url = '';
echo 'default derp';
}
So I have this block of code and it will not work for me. The url can say exactly what is in the case and it will default. I'm trying to get url structures to build out a shortcode and I need it to match what is entered.
I determined that if I enter just add a variable for a string for $url = 'brand-identity-evolution'; The switch works. I made sure it's a string with is_string function and can't figure out why this isn't working.
You added a PHP_EOL at the end of the URL, so all of your cases will fail because you're not checking for that. Remove your PHP_EOL and you'll be fine.
Related
I am trying to build an HTML without having to duplicate code.
Basically I have the option to print or save to file; option will be passed through $_GET.
I loop through a csv, so the HTML receive lots of variables.
I thought of having a variable $action;
If $action == 'view' then
echo "<h1>Hello World</h1>";
If $action == 'save' then
file_put_contents($file,"<h1>Hello World</h1>", FILE_APPEND);
I don't like the idea of having to repeat the code, with one section using echo and the other file_put_contents.
I know it's completly wrong, only trying to give the idea, is there a way of kind set a variable like this?
if ($action == "view") {$start = 'echo'; $end = ';';}
elseif ($action == "save") {$start = 'file_put_contents($file,'; $end = ', FILE_APPEND);';}
$start "<h1>Hello World</h1>" $end
Your code is completely wrong, syntax error.
But you can do this:
$str = '<h1>Hello World</h1>';
switch ($action) {
case 'view':
echo $str;
break;
case 'save':
file_put_contents($file, $str, FILE_APPEND);
break;
default:
throw new Exception('Invalid action');
}
I already create a geocode api on google console. I have a search box input with the google autocomplete in my site and I would like to set a specific city to my geocode api and integrate it in my web app. The city is: toulouse, Country: France.
When the customer type his address on the search box, I want it to only search all address in the city of toulouse, based on the center of toulouse with covered distance of 20 km.
Here is my code based on the file Function.php
public function geoCoding($lat='',$lng='')
{
$protocol = isset($_SERVER["https"]) ? 'https' : 'http';
if ($protocol=="http"){
$url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=".$lat.",".$lng."&sensor=true";
} else $url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=".$lat.",".$lng."&sensor=true";
$google_geo_api_key=getOptionA('google_geo_api_key');
if (!empty($google_geo_api_key)){
$url=$url."&key=".urlencode($google_geo_api_key);
}
$data = #file_get_contents($url);
if (!empty($data)){
$result = json_decode($data,true);
//dump($result);
if (!isset($result['results'])){
return false;
}
if (is_array($result['results']) && count($result['results'])>=2){
$location = array();
foreach ($result['results'][0]['address_components'] as $component) {
switch ($component['types']) {
case in_array('street_number', $component['types']):
$location['street_number'] = $component['long_name'];
break;
case in_array('route', $component['types']):
$location['street'] = $component['long_name'];
break;
case in_array('neighborhood', $component['types']):
$location['street2'] = $component['long_name'];
break;
case in_array('sublocality', $component['types']):
$location['sublocality'] = $component['long_name'];
break;
case in_array('locality', $component['types']):
$location['locality'] = $component['long_name'];
break;
case in_array('administrative_area_level_2', $component['types']):
$location['admin_2'] = $component['long_name'];
break;
case in_array('administrative_area_level_1', $component['types']):
$location['admin_1'] = $component['long_name'];
break;
case in_array('postal_code', $component['types']):
$location['postal_code'] = $component['long_name'];
break;
case in_array('country', $component['types']):
$location['country'] = $component['long_name'];
$location['country_code'] = $component['short_name'];
break;
}
}
return $location;
}
}
return false;
}
Your description sounds like you are using the Search Box widget in the Maps JavaScript API's Places library, but your code only shows use of reverse geocoding in the Geocoding API web service.
Since I think only the former makes sense, I'll venture you'll be interested in the following feature requests that would allow you to restrict autocomplete to a city:
Issue 8606: places bound restrict
Issue 4433: allow componentRestrictions to filter same components as the geocoding API service
For now, the options I know of are:
Set the Search box bounds to those of the city (which you can get from Geocoding API) and rely on the widget to prefer (not restrict) suggestions within those bounds, or
Build your own widget using AutocompleteService.getQueryPredictions() and do your own after-the-fact filtering to remove suggestions, but that would be very tricky because the name of the city will not necessarily always be part of the suggestion.
I am working on my website using wordpress to view and change cover for user by clicking on photo and then redirect him for example to process.php?pid=12
I am using
switch($GetPicId)
{
So I can't add more pic I but now I have script to upload pic using database, and I wanna to get id and pic location from by using database
First this is the upload script
and this is switch code
$GetPicId = $_GET["pid"]; // Picture ID from Index page
$PicLocation ='';
/*
Users do not need to know original location of image.
I think it's better to get image location from database using ID.
for demo here i'am using PHP switch.
*/
switch($GetPicId)
{
case 1:
$PicLocation = 'cover_pics/cover1.jpg';
break;
case 2:
$PicLocation = 'cover_pics/cover2.jpg';
break;
case 3:
$PicLocation = 'cover_pics/cover3.jpg';
break;
case 4:
$PicLocation = 'cover_pics/cover4.jpg';
break;
case 5:
$PicLocation = 'cover_pics/cover5.jpg';
break;
case 6:
$PicLocation = 'cover_pics/cover6.jpg';
break;
case 7:
$PicLocation = 'cover_pics/cover7.jpg';
break;
case 8:
$PicLocation = 'cover_pics/cover8.jpg';
break;
case 9:
$PicLocation = 'cover_pics/cover9.jpg';
break;
case 10:
$PicLocation = 'cover_pics/cover10.jpg';
break;
case 11:
$PicLocation = 'cover_pics/cover11.jpg';
break;
default:
header('Location: ' . $homeurl);
break;
}
Just Try
$GetPicId = $_GET["pid"]; // Picture ID from Index page
$sql=mysql_query("SELECT piclocation FROM tableName WHERE pid=$GetPicId") or die(mysql_error());
$res=mysql_fetch_array($sql);
$PicLocation = $res['piclocation '];
Use this to get attachment url ..Your cover images are uploaded in media right??
Then try this
<?php wp_get_attachment_url( $id ); ?>
it will become something like this
$GetPicId = $_GET["pid"]; // Picture ID from Index page
$PicLocation =wp_get_attachment_url( $GetPicId);
I know how to code a solution to my problem, I am just interested in the shortest way to code it. Thats the problem:
I am parsing a URL, the parsing can have 3 results, local, staging or production. I figure out which one it is using a regex. I do that in a function called getServer().
Now in that function I return an array which has 3 elements which are either 0 or 1. If the first is 1 and the other two are 0, it means, its a local server for example.
Now when I get that array back I still have to write an if to see which of the array elems is 1.
if($returnArrayFromFunction[0] == '1') {
// do the stuff for the local server case
}
if($returnArrayFromFunction[1] == '1') {
// do the stuff for the staging server case
}
if($returnArrayFromFunction[2] == '1') {
// do the stuff for the production server case
}
Is there some way to shorten that code?
Thanks for your time!
Don't return an array with the index of the value 1 encoding the result. Define three constants
define('SERVER_LOCAL', 1);
define('SERVER_STAGING', 2);
define('SERVER_PRODUCTION', 4);
And return the correct constant from your code, then use a switch statement
switch($serverType) {
case(SERVER_LOCAL)::
DoStuffForLocalServer();
break;
case ...
If terseness is your goal, shorten the switch to
$serverType == SERVER_LOCAL ? doLocal() : $serverType == SERVER_STAGING ? doStaging() : doProduction();
Is as short as it gets, but will probanly be frowned upon :-)
Why not just return an id number in getServer()?
$serverId = getServer();
switch ($serverId) {
case 0: // Local
// Code
break;
case 1: // Staging
// Code
break;
case 2: // Production
// Code
}
Note:
If you will need to use these server ids elsewhere in the code, it may be easier to keep track of which id corresponds to which server by using a naming convention with define(). This can also make your code easier to read and thus easier to debug.
define('SERVER_LOCAL', 0);
define('SERVER_STAGING', 1);
define('SERVER_PRODUCTION', 2);
Then you can replace the above switch with the following:
switch ($serverId) {
case SERVER_LOCAL:
// Code
break;
case SERVER_STAGING:
// Code
break;
case SERVER_PRODUCTION:
// Code
}
Try this code
$case=array_search(1,$returnArrayFromFunction);
switch($case)
{
0:
break;
// do the stuff for the local server case
1:
break;
// do the stuff for the staging server case
2:
// do the stuff for the production server case
break;
}
Try like
foreach($returnArrayFromFunction as $key=>$return)
{
if($return == '1')
{
switch($key)
{
case '0' : //Stuff at local
break;
case '1' : //Stuff at Staging
break;
case '2' : //Stuff at production
break;
}
}
}
$code = join('', $returnArrayFromFunction );
//something like '111' / '010' / '110'
switch( $code ){
case '111':
//all values 1
break;
case '001':
//something else
break;
}
Your getServer() function should just return one value instead of array. And then use following code:
$serverId = getServer();
switch ($serverId) {
case 0: // local server
// Your code
break;
case 1: // testing server
// Your code
break;
case 2: // live server
// Your code
}
Pretty simple question: which one of these two PHP (version 5+) header call is the "best"?
header('Not Modified', true, 304);
header('HTTP/1.1 304 Not Modified');
I'm pretty sure the first one is the most polyvalent one, but just curious if PHP would "fix" the second one if under HTTP 1.0...
Thanks!
Edit: One of these header crashes PHP on my Web host. Follow-up question at:
PHP header() call "crashing" script with HTTP 500 error
I would use this one:
header($_SERVER['SERVER_PROTOCOL'].' 304 Not Modified', true, 304);
$_SERVER['SERVER_PROTOCOL'] contains the protocol used in the request like HTTP/1.0 or HTTP/1.1.
Edit I have to admit that my suggestion is senseless. After a few tests I noticed that if the first parameter is a valid HTTP status line, PHP will use that status line regardless if and what second status code was given with the third parameter. And the second parameter (documentation names it replace) is useless too as there can not be multiple status lines.
So the second and third parameter in this call are just redundant:
header($_SERVER['SERVER_PROTOCOL'].' 304 Not Modified', true, 304);
Use just this instead:
header($_SERVER['SERVER_PROTOCOL'].' 304 Not Modified');
There are two things about the behaviour of the first header call that are worth pointing out:
If you provide the 3rd argument, PHP will ignore the first string argument and send the correct response for the given number. This might make the first method less prone to programmer errors.
PHP seems to respond with a HTTP/1.1 response even when the request was made with HTTP/1.0
I'd go with the second one, as the http response code argument is only supported >= PHP 4.3.0 (which could affect code portability).
I've done this many times and not come across any client that doesn't support HTTP/1.1, so unless you have a special case I shouldn't think that would ever be a problem.
I would normally go with the second example - however, when recently benchmarking an application using apachebench, we noticed ab hanging often.
After debugging, it was identified that the header in this style:
header('HTTP/1.1 304 Not Modified')
Was the culprit (Yeah, I have no idea) and after changing it to,
header('Not Modified', true, 304);
Believe it or not ab started working. Very strange but something to think about. I'll probably use the second method going forward.
For future reference the http_response_code() function is coming in 5.4:
http://www.php.net/manual/en/function.http-response-code.php
An alternative is:
if (!function_exists('http_response_code')) {
function http_response_code($code = NULL) {
if ($code !== NULL) {
switch ($code) {
case 100: $text = 'Continue'; break;
case 101: $text = 'Switching Protocols'; break;
case 200: $text = 'OK'; break;
case 201: $text = 'Created'; break;
case 202: $text = 'Accepted'; break;
case 203: $text = 'Non-Authoritative Information'; break;
case 204: $text = 'No Content'; break;
case 205: $text = 'Reset Content'; break;
case 206: $text = 'Partial Content'; break;
case 300: $text = 'Multiple Choices'; break;
case 301: $text = 'Moved Permanently'; break;
case 302: $text = 'Moved Temporarily'; break;
case 303: $text = 'See Other'; break;
case 304: $text = 'Not Modified'; break;
case 305: $text = 'Use Proxy'; break;
case 400: $text = 'Bad Request'; break;
case 401: $text = 'Unauthorized'; break;
case 402: $text = 'Payment Required'; break;
case 403: $text = 'Forbidden'; break;
case 404: $text = 'Not Found'; break;
case 405: $text = 'Method Not Allowed'; break;
case 406: $text = 'Not Acceptable'; break;
case 407: $text = 'Proxy Authentication Required'; break;
case 408: $text = 'Request Time-out'; break;
case 409: $text = 'Conflict'; break;
case 410: $text = 'Gone'; break;
case 411: $text = 'Length Required'; break;
case 412: $text = 'Precondition Failed'; break;
case 413: $text = 'Request Entity Too Large'; break;
case 414: $text = 'Request-URI Too Large'; break;
case 415: $text = 'Unsupported Media Type'; break;
case 500: $text = 'Internal Server Error'; break;
case 501: $text = 'Not Implemented'; break;
case 502: $text = 'Bad Gateway'; break;
case 503: $text = 'Service Unavailable'; break;
case 504: $text = 'Gateway Time-out'; break;
case 505: $text = 'HTTP Version not supported'; break;
default:
exit('Unknown http status code "' . htmlentities($code) . '"');
break;
}
$protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
header($protocol . ' ' . $code . ' ' . $text);
$GLOBALS['http_response_code'] = $code;
} else {
$code = (isset($GLOBALS['http_response_code']) ? $GLOBALS['http_response_code'] : 200);
}
return $code;
}
}
In this example I am using $GLOBALS, but you can use whatever storage mechanism you like... I don't think there is a way to return the current status code:
https://bugs.php.net/bug.php?id=52555
For reference the error codes I got from PHP's source code:
http://lxr.php.net/opengrok/xref/PHP_5_4/sapi/cgi/cgi_main.c#354
And how the current http header is sent, with the variables it uses:
http://lxr.php.net/opengrok/xref/PHP_5_4/main/SAPI.c#856
I think Gumbo's answer is the most sensible so far. However try this:
<?php
header('Gobbledy Gook', true, 304);
?>
If the first string is not a proper header it is discarded. If iy does look like a valid header it is appended to the headers - try this:
<?php
header('Cache-Control: max-age=10', true, 304);
?>
The manual for header() and note the special cases - in general I think its not advisable to rely on such built-in heuristics.
However, I'm guessing that your actually interested in getting the content cached well by proxies/browsers. In most instances, latency is far more of a problem of a problem than bandwidth. Next consider how a browser behaves when cached content is stale - in the absence of updated caching information, it keeps making repeated requests to the server to see if the content is still stale.
I.e. in most cases ignoring the conditional part of requests (or even better stripping them on the webserver) actually improves performance.